package cn.com.dashihui.api.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.GroupCode;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.PayCode;
import cn.com.dashihui.api.common.ResultMap;
import cn.com.dashihui.api.dao.Goods;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderE;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderGLog;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.OrderZ;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.api.service.GroupbuyingService;
import cn.com.dashihui.api.service.OrderService;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.kit.KdniaoTrackQueryAPI;
import cn.com.dashihui.pay.SQ.SQpay;
import cn.com.dashihui.pay.SQ.Kit.ParamUtils;
import cn.com.dashihui.pay.ZY.EncryUtils;
import cn.com.dashihui.pay.ZY.ZYPay;
import cn.com.dashihui.pay.alipay.sign.SignUtils;
import cn.com.dashihui.pay.wx.kit.HttpsRequest;
import cn.com.dashihui.pay.wx.kit.Signature;
import cn.com.dashihui.pay.wx.kit.UtilKit;
import cn.com.dashihui.pay.wx.request.PreOrderReqData;
import cn.com.dashihui.pay.wx.request.QueryOrderReqData;
import cn.com.dashihui.pay.wx.response.PreOrderResData;
import cn.com.dashihui.pay.wx.response.QueryOrderResData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Before(AuthLoginInterceptor.class)
public class OrderController extends BaseController {

	//使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService service = Duang.duang(OrderService.class);
	private GroupbuyingService groupService = Duang.duang(GroupbuyingService.class);
	
	/**
	 * 保存订单<br/>
	 * 在保存订单时，需要验证<br/>
	 * 1.验证所购买商品是否是“上架”状态
	 * 2.对商品数量是否超过限购数量作验证，如果不符合则保存不在成功
	 * 3.验证客户端提交过来的订单总金额和服务端计算出来的总金额是否一致
	 * @param GOODSID 商品ID
	 * @param COUNT 购买数量
	 * @param AMOUNT 总金额
	 * @param LINKNAME 联系人姓名
	 * @param TEL 电话
	 * @param ADDRESS 地址
	 * @param DESCRIBE 订单备注
	 * @param ISREDEEM 是否使用优惠券    0 纯现金支付，1兑换  2团购
	 */
	
	public void save(){
		String goodIds = getPara("GOODSID");
		String counts = getPara("COUNT");	//购买数量
		String sid = getPara("SID");	//购买商品模板ID
		String amoun = getPara("AMOUNT");	//购买金额
		String linkName = getPara("LINKNAME");	//联系人名称
		String tel = getPara("TEL");		//联系人电话
		String address = getPara("ADDRESSID");	//联系人地址
		String describe = getPara("DESCRIBE");	//联系人备注
		int isRedeem = getParaToInt("ISREDEEM",0);	//是否使用优惠券  0 纯现金支付，1兑换  2团购
		String zsactivity = getPara("ZSACTIVITY");	//是否赠送
		String zscouponnum = getPara("ZSCOUPONNUM"); //赠送优惠券
		String zsdedunum = getPara("ZSDEDUNUM");	//赠送抵扣券
		String zspointnum = getPara("ZSPOINTNUM");	//赠送积分
		String isSpike = getPara("SPIKE");//是否秒杀
		if(StrKit.isBlank(isSpike)){
			isSpike = "0";
		}
		String spikeid = getPara("SPIKEID");//秒杀id
		if("1".equals(isSpike)){
			
			if(StrKit.isBlank(spikeid)){
				renderFailed("参数SPIKEID不能为空");
	    		return;
			}
		}
		if(StrKit.isBlank(goodIds)){
			renderFailed("参数STOREID不能为空");
    		return;
		}else if(StrKit.isBlank(counts)){
			renderFailed("参数COUNT不能为空");
    		return;
		}else if(StrKit.isBlank(address)){
			renderFailed("参数ADDRESS不能为空");
    		return;
		}else if(!StrKit.isBlank(describe)&&describe.length()>=200){
			renderFailed("参数DESCRIBE内容过长");
    		return;
		}else if(isRedeem == 0){
				Double amount = Double.parseDouble(amoun);

				//普通订单
				//普通订单的订单编号，以大写字母G开头
				String orderNumStore = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				/**
				 * 验证用户要购买的自营商品
				 * 1.验证是否有商品已下架
				 * 2.验证是否有商品购买量已经超过了今日所限量
				 * 3.验证总金额是否与客户端的入参总金额相同
				 */
				
				int validateSelfGoods = service.validate(getCurrentUser().getInt("id"),
						goodIds,counts,amount,sid,isSpike,isRedeem,zsactivity,zscouponnum,zsdedunum,zspointnum);
				if(validateSelfGoods==1){
					renderFailed("您所购买的亿品直供商品中有已下架的商品");
					return;
				}else if(validateSelfGoods==2){
					renderFailed("您所购买的亿品直供商品中有超出限量的商品");
					return;
				}else if(validateSelfGoods==3){
					renderFailed("总金额计算不正确");
					return;
				}
				Record add = Db.findById("t_bus_user_address", address);
				if(add == null){
					renderFailed("地址有误");
					return;
				}
				//保存自营商品订单
				Order selfOrder = new Order()
						.set("orderNum", orderNumStore)
						.set("userid", getCurrentUser().getInt("id"))
						.set("countnum", counts)
						.set("amount", amount)
						.set("payState", OrderCode.OrderPayState.NO_PAY)
						.set("goodsid", goodIds)
						.set("orderState", OrderCode.OrderState.NORMAL)
						.set("tel", tel)
						.set("specsid", sid)
						.set("addressid", address)
						.set("isSpike", isSpike)
						.set("receivename", add.get("linkname"))
						.set("receiveaddress", add.get("address"))
						.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
				// 秒杀剩余时间单独计算
				if("1".equals(isSpike)){
					selfOrder.set("spikeid", spikeid)
							 .set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.spike"), "yyyy-MM-dd HH:mm:ss"));
				}else{
					selfOrder.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"));
				}
				if(zsactivity.equals("2")){
					if(!StrKit.isBlank(zscouponnum)){
						selfOrder.set("jypoint",zscouponnum);//赠送优惠券
					}
					if(!StrKit.isBlank(zsdedunum)){
						selfOrder.set("jkpoint",zsdedunum);//赠送抵扣券
					}
					if(!StrKit.isBlank(zspointnum)){
						selfOrder.set("sppoint",zspointnum);//赠送积分
					}
				}
				//用户如填写了备注，则记录
				if(StrKit.notBlank(describe)){
					selfOrder.set("describe", describe);
				}
				int forwardFlag = 0;
//				Order storeOrder = null;
				try {
					forwardFlag = service.doRedeem(selfOrder,goodIds,counts,getCurrentUser().getInt("id"),isRedeem,sid,amount,Integer.parseInt(isSpike));
				} catch (Exception e) {
					renderFailed("网络繁忙...，请稍后重试");
					return;
				}
				renderSuccess(ResultMap.newInstance().put("ORDERNUM",orderNumStore).put("AMOUNT", amount).put("FORWARDFLAG", forwardFlag));
			
		}else if (isRedeem == 1){
			 //生成兑换订单
			Double amount = Double.parseDouble(amoun);
			//兑换订单的订单编号，以大写字母D开头
			String orderNumStore = "D"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
			/**
			 * 验证用户要购买的自营商品
			 * 1.验证是否有商品已下架
			 * 2.验证是否有商品购买量已经超过了今日所限量
			 * 3.验证总金额是否与客户端的入参总金额相同
			 */
			int validateSelfGoods = service.validate(getCurrentUser().getInt("id"),
					goodIds,counts,amount,sid,isSpike,isRedeem,zsactivity,zscouponnum,zsdedunum,zspointnum);
			if(validateSelfGoods==1){
				renderFailed("您所购买商品已下架或售罄商品");
				return;
			}else if(validateSelfGoods==2){
				renderFailed("您所购买的商品中有超出限量的商品");
				return;
			}else if(validateSelfGoods==3){
				renderFailed("总金额计算不正确");
				return;
			}else if(validateSelfGoods==4){
				renderFailed("积分、惠券、抵扣券余额不足");
				return;
			}
			Record add = Db.findById("t_bus_user_address", address);
			if(add == null){
				renderFailed("地址有误");
				return;
			}
			//保存自营商品订单
			OrderE selfOrder = new OrderE()
					.set("orderNum", orderNumStore)
					.set("userid", getCurrentUser().getInt("id"))
					.set("countnum", counts)
					.set("amount", amount)
					.set("payState", OrderCode.OrderPayState.NO_PAY)
					.set("goodsid", goodIds)
					.set("orderState", OrderCode.OrderState.NORMAL)
					.set("tel", tel)
					.set("specsid", sid)
					.set("addressid", address)
					.set("receivename", add.get("linkname"))
					.set("receiveaddress", add.get("address"))
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
					.set("jypoint",-Double.parseDouble(zscouponnum))//赠送优惠券
					.set("jkpoint",-Double.parseDouble(zsdedunum))//赠送抵扣券
					.set("sppoint",-Double.parseDouble(zspointnum));//赠送积分
			//用户如填写了备注，则记录
			if(StrKit.notBlank(describe)){
				selfOrder.set("describe", describe);
			}
			int forwardFlag = 0;
			try {
				// 商品数量的更改
				forwardFlag = service.doRedeemE(selfOrder,goodIds,counts,getCurrentUser().getInt("id"),sid,amount);
			} catch (Exception e) {
//				renderFailed("保存订单失败");
				renderFailed("网络繁忙...，请稍后重试");
				return;
			}
			renderSuccess(ResultMap.newInstance().put("ORDERNUM",orderNumStore).put("AMOUNT", amount).put("FORWARDFLAG", forwardFlag));
		}  
		//else if (){}   //生成团购订单
		
	}
	
	/**
	 * 保存在线充值订单<br/>
	 * 在保存订单时，需要验证<br/>
	 * 1.验证所购买商品是否是“上架”状态
	 * 2.对商品数量是否超过限购数量作验证，如果不符合则保存不在成功
	 * 3.验证客户端提交过来的订单总金额和服务端计算出来的总金额是否一致
	 * @param GOODSID 商品ID
	 * @param COUNT 购买数量
	 * @param AMOUNT 总金额
	 * @param ISREDEEM 是否使用优惠券    0 纯现金支付，1兑换  2团购
	 */
	
	public void save1(){
		String goodIds = getPara("GOODSID");
		String counts = getPara("COUNT");	//购买数量
		String amoun = getPara("AMOUNT");	//购买金额
		String zsactivity = getPara("ZSACTIVITY");	//是否赠送
		String zscouponnum = getPara("ZSCOUPONNUM"); //赠送优惠券
		String zsdedunum = getPara("ZSDEDUNUM");	//赠送抵扣券
		String zspointnum = getPara("ZSPOINTNUM");	//赠送积分
		if(StrKit.isBlank(goodIds)){
			renderFailed("参数GOODSID不能为空");
    		return;
		}else if(StrKit.isBlank(counts)){
			renderFailed("参数COUNT不能为空");
    		return;
		}
		Double amount = Double.parseDouble(amoun);

		//在线订单
		//在线订单的订单编号，以大写字母Z开头
		String orderNumStore = "Z"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		/**
		 * 验证用户要购买的自营商品
		 * 1.验证是否有商品已下架
		 * 2.验证是否有商品购买量已经超过了今日所限量
		 * 3.验证总金额是否与客户端的入参总金额相同
		 */
		
		int validateSelfGoods = service.validate1(getCurrentUser().getInt("id"),goodIds,counts,amount);
		if(validateSelfGoods==1){
			renderFailed("您所购买的商品已下架");
			return;
		}else if(validateSelfGoods==3){
			renderFailed("金额计算不正确");
			return;
		}
		
		//保存自营商品订单
		int goodIdsInt=Integer.valueOf(goodIds);
		OrderZ selfOrder = new OrderZ()
				.set("orderNum", orderNumStore)
				.set("userid", getCurrentUser().getInt("id"))
				.set("countnum", counts)
				.set("amount", amount)
				.set("payState", OrderCode.OrderPayState.NO_PAY)
				.set("goodsid", goodIdsInt)
				.set("orderState", OrderCode.OrderState.NORMAL)
				.set("jypoint",Double.parseDouble(zscouponnum))//赠送优惠券
				.set("jkpoint",Double.parseDouble(zsdedunum))//赠送抵扣券
				.set("sppoint",Double.parseDouble(zspointnum))//赠送积分
				.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"));
		try {
			if(!service.saveZ(selfOrder,getCurrentUser().getInt("toBossThreeId"))){
				renderFailed("保存充值订单失败");
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("保存充值订单失败");
			return;
		}
		renderSuccess(ResultMap.newInstance().put("ORDERNUM",orderNumStore).put("AMOUNT", amount).put("FORWARDFLAG", 1));
	}
	
	/**
	 * 客户端确认去支付<br/>
	 * 首先验证支付方式参数，并验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * 然后根据所选择的支付方式，向不同平台发起支付请求<br/>
	 * 目前只申请了微信支付平台，2015/12/02
	 * @param ORDERNUM 要支付的订单号
	 * @param FLAG 用户所选择的支付方式，1:微信支付 3.支付宝支付 4银联付款 5余额
	 * @param SQPayMethod 如果是银联付款, 1 发短信  2 验证短信
	 * @param CODE 如果是验证短信  此为发送短信返回的验证码
	 * @param TIME 如果是验证短信  此为发送短信返回的时间日期
	 * @throws AlipayApiException 
	 * 
	 */
	public void pay(){
		String orderNum = getPara("ORDERNUM");
		String flagStr = getPara("FLAG");
		String token=getPara("TOKENP");
		
		if("5".equals(flagStr)){
			if(StrKit.isBlank(token)){
				renderFailed("参数TOKENP不能为空");
	    		return;
			}
		}
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if("0".equals(flagStr)){
			renderFailed("请选择支付方式");
    		return;
		}
		String str = orderNum.subSequence(0, 1).toString();
		if("G".equals(str)){
			//普通订单
			//查询订单详情并以此验证订单号
			Order order = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			if(order.getInt("isSpike") == 1){
				//数据准备
				String id = order.get("goodsid");
				String[] times = order.getTimestamp("startDate").toString().split(" ");
				int count  = service.checkSpikeOrderDate(id,times);
				if(count == -1){
					renderFailed("您的订单已过秒杀时间段,无法支付");
					return;
				}
			}
			//订单总金额
			double amount = order.get("amount");
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flagStr);
			if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
				//1：微信支付
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				//获取客户端IP
				String remoteip = EncryUtils.getRealIp(getRequest());
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				
//				int count = 0;
//				String head = getRequest().getHeader("User-Agent");
//				if(head.indexOf("iPhone")!=-1){
//					count = 1;
//				}else if(head.indexOf("Android")!=-1){
//					count = 2;
//				}else{
//					count = 3;
//				}
				//向微信发起预支付请求
				PreOrderReqData preOrderReqData = new PreOrderReqData("亿品直供",orderNum,amountStr,remoteip,PropKit.get("weixinpay.goodsOrderNotifyUrl"),startDate,expireDate);
				PreOrderResData preOrderRspData = null;
				try {
					preOrderRspData = (PreOrderResData)UtilKit.getObjectFromXML(new HttpsRequest().post(PropKit.get("weixinpay.unifiedorder"), preOrderReqData), PreOrderResData.class);
				}catch(Exception e){
					renderFailed("网络错误，请稍后重试");
		    		return;
				}
				//预支付完成
				if(preOrderRspData!=null){
					System.out.println("Response....:"+preOrderReqData);
					//保存接口请求记录
					String sendContent = UtilKit.getXMLFromObject(preOrderReqData);
					String returnContent = UtilKit.getXMLFromObject(preOrderRspData);
					new OrderPayAPIRecord().set("orderNum", orderNum)
						.set("sendContent", sendContent)
						.set("returnContent", returnContent)
						.set("payMethod", payMethod)
						.set("flag", 1)
						.save();
					if(preOrderRspData.getReturn_code().equals("SUCCESS")&&preOrderRspData.getResult_code().equals("SUCCESS")){
						//更新订单支付方式为微信
						order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
						//向客户端返回结果
						String noncestr = CommonKit.getRandomStringByLength(32);
						String timestamp = DatetimeKit.getTimestamp();
						String url = PropKit.get("weixinpay.redirect_url");
						try {
							url = URLEncoder.encode(url, "GBK");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							renderFailed("编码转换错误");
				    		return;
						}
						url = preOrderRspData.getMweb_url()+ "&redirect_url=" +url + "?ORDERNUM="+orderNum ;
						renderSuccess(ResultMap.newInstance()
								.put("APPID", preOrderReqData.getAppid())
								.put("PARTNERID", preOrderReqData.getMch_id())
								.put("PREPAYID", preOrderRspData.getPrepay_id())
								.put("URL",url)
								.put("PACKAGE", "Sign=WXPay")
								.put("NONCESTR", noncestr)
								.put("TIMESTAMP", timestamp)
								.put("SIGN", Signature.getSign(ResultMap.newInstance()
										.put("appid", preOrderReqData.getAppid())
										.put("partnerid", preOrderReqData.getMch_id())
										.put("prepayid", preOrderRspData.getPrepay_id())
										.put("package", "Sign=WXPay")
										.put("noncestr", noncestr)
										.put("timestamp", timestamp).getAttrs())));
						return;
					}
				}
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
				System.out.println("H5进入支付宝支付");
				//2：支付宝支付
				//获取订单总金额，并转换为以“元”为单位
				String amountStr1 = String.valueOf(Double.valueOf(amount)).toString();
				String gateway=PropKit.get("applipay.url");
				String app_id=PropKit.get("appalipay.partner");
				String privateKey=PropKit.get("appalipay.privateKey");
				String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
				String charset=PropKit.get("applipay.charset");
				String sign_type=PropKit.get("applipay.signType");
				String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
				String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
				String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
				String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
				String alipay_return_url =PropKit.get("appalipay.returnUrl");
				
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				
				
				
				
				AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
				model.setOutTradeNo(orderNum);
				model.setTotalAmount(amountStr1);
				model.setSubject("亿拼惠");
				model.setProductCode("QUICK_WAP_WAY");
				
				AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
				alipayRequest.setBizModel(model);
				alipayRequest.setNotifyUrl(alipay_notify_url);
				alipayRequest.setReturnUrl(alipay_return_url);
				
				DefaultAlipayClient alipayClient;
				try {
					alipayClient = new DefaultAlipayClient(certAlipayRequest);
					AlipayTradeWapPayResponse response= alipayClient.pageExecute(alipayRequest);
					
					new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", alipayRequest.getBizModel().toString())
					.set("returnContent", response.getBody())
					.set("payMethod", payMethod)
					.set("flag", 1)
					.save();
					//更新订单支付方式为支付宝
					order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
					//将结果返回给客户端
					renderSuccess(ResultMap.newInstance().put("URL", response.getBody()).getAttrs());
					return;
				} catch (AlipayApiException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					renderFailed("支付宝支付错误");
					return;
				}
				
				
			}else if(payMethod == OrderCode.OrderPayMethod.SEL){

				//银联支付阶段   1 发送短信  2验证短信
				String sqPayMethod = getPara("SQPayMethod");
				if(StrKit.isBlank(sqPayMethod)){
					renderFailed("参数CODE不能为空");
		    		return;
				}
				//根据用户银联支付的阶段不同作不同处理
				int SQPayMethod = Integer.valueOf(sqPayMethod);
				//查询用户默认卡号和信息
				Record card = service.findUserCard(getCurrentUser().getInt("id"));
				if(card == null){
					renderFailed("该用户没有默认付款卡信息");
		    		return;
				}
				
				//更新订单支付方式为银联
				order.set("paytype", OrderCode.OrderPayMethod.SEL).update();
				
				//若为发送短信阶段
				if(SQPayMethod == OrderCode.SQPayMethod.MSM){
					//创建信息对象
					Map<String,String> dataMap = new HashMap<String ,String>();
					dataMap.put("custName", card.get("custName"));
					dataMap.put("cardNo", card.get("cardNo"));
					dataMap.put("phoneNo", card.get("phoneNo"));
					dataMap.put("idNo", card.get("idNo"));
					dataMap.put("payAmount", amount+"");//金额
//					dataMap.put("payAmount", "0.01");//金额
					dataMap.put("merOrderNo", orderNum);//订单号
					dataMap.put("bankCode", card.get("bankCode"));
					dataMap.put("cardType", card.get("cardType"));
					dataMap.put("purpose", "");//商户备注
					
					Map<String,String> map = null;
					//支付短信
					try {
						map = SQpay.payMsg(dataMap);
					} catch (Exception e) {
//						e.printStackTrace();
						renderFailed("支付错误");
			    		return;
					}
					//将结果返回给客户端
					if(map.get("resFlag").equals("success")){
						renderSuccess(ResultMap.newInstance().put("TIME", map.get("txnTime")));
					}else{
						renderFailed("短信发送失败");
					}
					return;
					//若是验证短信
				}else if(SQPayMethod == OrderCode.SQPayMethod.CODE){
					String code = getPara("CODE");
					String txnTime = getPara("TIME");
					if(StrKit.isBlank(code)){
						renderFailed("参数CODE不能为空");
			    		return;
					}else if(StrKit.isBlank(txnTime)){
						renderFailed("参数TIME不能为空");
			    		return;
					}
					//创建信息对象
					Map<String,String> dataMap = new HashMap<String ,String>();
					dataMap.put("merOrderNo", orderNum);//订单号
					dataMap.put("cardNo", card.get("cardNo"));
					dataMap.put("custName", card.get("custName"));
					dataMap.put("idNo", card.get("idNo"));
					dataMap.put("phoneNo", card.get("phoneNo"));
					dataMap.put("purpose", "");//商户备注
//					dataMap.put("payAmount", amount);//金额
					dataMap.put("payAmount", "0.01");//金额
					dataMap.put("bankCode", card.get("bankCode"));
					dataMap.put("txnTime", txnTime);//短信返回交易时间
					dataMap.put("smsCode", code);//信息
					//支付短信
					Map<String,String> map = null;
					try {
						map = SQpay.pay(dataMap);
					} catch (Exception e) {
//						e.printStackTrace();
						renderFailed("支付错误");
			    		return;
					}
					//将结果返回给客户端
					if(map.get("resFlag").equals("success")){
						renderSuccess(ResultMap.newInstance().put("responseCode", map.get("responseCode")));
						return;
					}else{
						renderFailed(map.get("resMess"));
						return;
					}
					
				}
				
			}else if(payMethod == OrderCode.OrderPayMethod.BALANCE){
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE).update();
				//查询用户余额  判断是否充足
				Map<String,String> map = new HashMap<String,String>();
				map.put("token", token);
				JSONObject js = ZYPay.find(map);
				Map<String, Object> resMap =EncryUtils.toMap(js);
				if("000000".equals(resMap.get("result"))){
		    		//查询成功
					JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
					JSONArray array = JSONArray.fromObject(jsondata.get("DATA"));
					jsondata = JSONObject.fromObject(array.get(0));
					if(service.saveMoneyUp(jsondata.getDouble("SUMMONEY"),getCurrentUser().getInt("id"))!=1){
//						renderFailed("更新余额失败");
						renderFailed("网络繁忙...，请稍后重试");
			    		return;
					}
//					amount = 0.01;
		    		//账户余额
					Double money = jsondata.getDouble("SUMMONEY");
					if(Double.compare(money, amount)==-1){
//						余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					User user = service.findUserByid(getCurrentUser().getInt("id"));
					Map<String,String> map1 = new HashMap<String,String>();
					String orderid = "Z"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(4);
					map1.put("order_type", PayCode.ORDERTYPE.MONEYPAY);//下单类型 2在线支付
					map1.put("order_id", orderid);
					map1.put("pay_firmid", user.get("payid")+"");
					map1.put("pay_firmname", user.get("name"));
					map1.put("pay_phone", user.get("phone"));
					String isPC = EncryUtils.JudgeIsMoblie(getRequest());
					map1.put("terminal_type", isPC);
					if("1".equals(isPC)){
						map1.put("terminal_num","MAC");
					}else if("2".equals(isPC)){
						map1.put("terminal_num","IMEI");
					}else{
						map1.put("terminal_num","OTHER");
					}
					String ip = EncryUtils.getRealIp(getRequest());
					map1.put("order_ip", ip);
					String money1 = new DecimalFormat("0.00").format(amount);
					map1.put("order_money",money1);
					Double orderfree =0.00;
					String format = new DecimalFormat("0.00").format(orderfree);
					map1.put("order_fee",format);
					map1.put("token",token);
					JSONObject jss = null;
					try {
						jss =ZYPay.createOrder(map1);
					} catch (Exception e) {
						renderFailed("Base64转换失败");
						return;
					}
					Map<String, Object> resMap1 =EncryUtils.toMap(jss);
					if("000000".equals(resMap1.get("result"))){
			    		//支付
						JSONObject jsondata1 = JSONObject.fromObject(resMap1.get("data"));
						if(Db.findFirst("SELECT * FROM t_bus_user_pay_orderid WHERE ischeck=1 AND fromOrderNum=?",orderNum)!=null){
							renderFailed("订单重复提交");
							return;
						}
						//创建订单表
						Record re = new Record().set("orderid",orderid)
												.set("fromOrderNum", orderNum)
												.set("userid", user.getInt("id"))
												.set("type", 1)
												.set("ischeck", 0)
												.set("money", money1)
												.set("moneyfree", format)
												.set("createDate", new Date());
						if(!Db.save("t_bus_user_pay_orderid", re)){
							renderFailed("网络错误，请稍后重试");
							return;
						}
						System.out.println(">>>>>>>>>>>>>>>"+jsondata1.get("location_url"));
			    		renderSuccess(jsondata1.get("location_url"));
			    		return;
			    	}else{
			    		//支付失败
			    		renderFailed((String)resMap1.get("msg"));
			    		return;
			    	}
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
			logger.info(">>>>>>>>>>>>>>>没有该支付方式");
			renderFailed("网络错误，请稍后重试");
			return;
		}else if("D".equals(str)){
			OrderE order = service.getExchangeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			
			//计算订单总金额
			double amount = order.getDouble("amount");
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flagStr);
			
			if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
				//1：微信支付
				//获取客户端IP
				String remoteip = CommonKit.getClientIp(getRequest());
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			
				//向微信发起预支付请求
				PreOrderReqData preOrderReqData = new PreOrderReqData("亿品直供",orderNum,amountStr,remoteip,PropKit.get("weixinpay.goodsOrderNotifyUrl"),startDate,expireDate);
				PreOrderResData preOrderRspData = null;
				try {
					preOrderRspData = (PreOrderResData)UtilKit.getObjectFromXML(new HttpsRequest().post(PropKit.get("weixinpay.unifiedorder"), preOrderReqData), PreOrderResData.class);
				}catch(Exception e){
					logger.info(">>>>>>>>>>>>>>>我信支付错误");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
				}
				//预支付完成
				if(preOrderRspData!=null){
					System.out.println("Response....:"+preOrderReqData);
					//保存接口请求记录
					String sendContent = UtilKit.getXMLFromObject(preOrderReqData);
					String returnContent = UtilKit.getXMLFromObject(preOrderRspData);
					new OrderPayAPIRecord().set("orderNum", orderNum)
						.set("sendContent", sendContent)
						.set("returnContent", returnContent)
						.set("payMethod", payMethod)
						.set("flag", 1)
						.save();
					if(preOrderRspData.getReturn_code().equals("SUCCESS")&&preOrderRspData.getResult_code().equals("SUCCESS")){
						//更新订单支付方式为微信
						order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
						//向客户端返回结果
						String noncestr = CommonKit.getRandomStringByLength(32);
						String timestamp = DatetimeKit.getTimestamp();
						String url = PropKit.get("weixinpay.redirect_url");
						url = "http://api.nczywc.cn/h5/#/pages/money/paySuccess";
						try {
							url = URLEncoder.encode(url, "GBK");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							renderFailed("编码转换错误");
				    		return;
						}
						url = preOrderRspData.getMweb_url()+ "&redirect_url=" +url + "?ORDERNUM="+orderNum ;
						renderSuccess(ResultMap.newInstance()
								.put("APPID", preOrderReqData.getAppid())
								.put("PARTNERID", preOrderReqData.getMch_id())
								.put("PREPAYID", preOrderRspData.getPrepay_id())
								.put("URL",url)
								.put("PACKAGE", "Sign=WXPay")
								.put("NONCESTR", noncestr)
								.put("TIMESTAMP", timestamp)
								.put("SIGN", Signature.getSign(ResultMap.newInstance()
										.put("appid", preOrderReqData.getAppid())
										.put("partnerid", preOrderReqData.getMch_id())
										.put("prepayid", preOrderRspData.getPrepay_id())
										.put("package", "Sign=WXPay")
										.put("noncestr", noncestr)
										.put("timestamp", timestamp).getAttrs())));
						return;
					}
				}
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
				System.out.println("H5进入支付宝支付");
				//2：支付宝支付
				//获取订单总金额，并转换为以“元”为单位
				String amountStr1 = String.valueOf(Double.valueOf(amount)).toString();
				String gateway=PropKit.get("applipay.url");
				String app_id=PropKit.get("appalipay.partner");
				String privateKey=PropKit.get("appalipay.privateKey");
				String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
				String charset=PropKit.get("applipay.charset");
				String sign_type=PropKit.get("applipay.signType");
				String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
				String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
				String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
				String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
				String alipay_return_url =PropKit.get("appalipay.returnUrl");
				
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				
				
				
				
				AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
				model.setOutTradeNo(orderNum);
				model.setTotalAmount(amountStr1);
				model.setSubject("亿拼惠兑换订单");
				model.setProductCode("QUICK_WAP_WAY");
				
				AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
				alipayRequest.setBizModel(model);
				alipayRequest.setNotifyUrl(alipay_notify_url);
				alipayRequest.setReturnUrl(alipay_return_url);
				
				DefaultAlipayClient alipayClient;
				try {
					alipayClient = new DefaultAlipayClient(certAlipayRequest);
					AlipayTradeWapPayResponse response= alipayClient.pageExecute(alipayRequest);
					
					new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", alipayRequest.getBizModel().toString())
					.set("returnContent", response.getBody())
					.set("payMethod", payMethod)
					.set("flag", 1)
					.save();
					//更新订单支付方式为支付宝
					order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
					//将结果返回给客户端
					renderSuccess(ResultMap.newInstance().put("URL", response.getBody()).getAttrs());
					return;
				} catch (AlipayApiException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					renderFailed("支付宝支付错误");
					return;
				}
				
			}else if(payMethod == OrderCode.OrderPayMethod.BALANCE){
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE).update();
				//查询用户余额  判断是否充足
				Map<String,String> map = new HashMap<String,String>();
				map.put("token", token);
				JSONObject js = ZYPay.find(map);
				Map<String, Object> resMap =EncryUtils.toMap(js);
				if("000000".equals(resMap.get("result"))){
		    		//查询成功
					JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
					JSONArray array = JSONArray.fromObject(jsondata.get("DATA"));
					jsondata = JSONObject.fromObject(array.get(0));
					if(service.saveMoneyUp(jsondata.getDouble("SUMMONEY"),getCurrentUser().getInt("id"))!=1){
			    		renderFailed("网络错误，请稍后重试");
			    		return;
					}
		    		//账户余额
					Double money = jsondata.getDouble("SUMMONEY");
					if(Double.compare(money, amount)==-1){
//						余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					User user = service.findUserByid(getCurrentUser().getInt("id"));
					Map<String,String> map1 = new HashMap<String,String>();
					String orderid = "Z"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(4);
					map1.put("order_type", PayCode.ORDERTYPE.MONEYPAY);//下单类型 2在线支付
					map1.put("order_id", orderid);
					map1.put("pay_firmid", user.get("payid")+"");
					map1.put("pay_firmname", user.get("name"));
					map1.put("pay_phone", user.get("phone"));
					String isPC = EncryUtils.JudgeIsMoblie(getRequest());
					map1.put("terminal_type", isPC);
					if("1".equals(isPC)){
						map1.put("terminal_num","MAC");
					}else if("2".equals(isPC)){
						map1.put("terminal_num","IMEI");
					}else{
						map1.put("terminal_num","OTHER");
					}
					String ip = EncryUtils.getRealIp(getRequest());
					map1.put("order_ip", ip);
					String money1 = new DecimalFormat("0.00").format(amount);
					map1.put("order_money",money1);
					Double orderfree =0.00;
					String format = new DecimalFormat("0.00").format(orderfree);
					map1.put("order_fee",format);
					map1.put("token",token);
					JSONObject jss = null;
					try {
						jss =ZYPay.createOrder(map1);
					} catch (Exception e) {
						renderFailed("Base64转换失败");
						return;
					}
					Map<String, Object> resMap1 =EncryUtils.toMap(jss);
					if("000000".equals(resMap1.get("result"))){
			    		//支付
						JSONObject jsondata1 = JSONObject.fromObject(resMap1.get("data"));
						if(Db.findFirst("SELECT * FROM t_bus_user_pay_orderid WHERE ischeck=1 AND fromOrderNum=?",orderNum)!=null){
							renderFailed("订单重复提交");
							return;
						}
						//创建订单表
						Record re = new Record().set("orderid",orderid)
												.set("fromOrderNum", orderNum)
												.set("userid", user.getInt("id"))
												.set("type", 1)
												.set("ischeck", 0)
												.set("money", money1)
												.set("moneyfree", format)
												.set("createDate", new Date());
						if(!Db.save("t_bus_user_pay_orderid", re)){
							logger.info(">>>>>>>>>>>>>>>纪录保存失败");
				    		renderFailed("网络错误，请稍后重试");
							return;
						}
			    		renderSuccess(jsondata1.get("location_url"));
			    		return;
			    	}else{
			    		//支付失败
			    		renderFailed((String)resMap1.get("msg"));
			    		return;
			    	}
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
			logger.info(">>>>>>>>>>>>>>>没有改支付方式");
    		renderFailed("网络错误，请稍后重试");
			return;
			
		}else if("Z".equals(str)){
			OrderZ order = service.getRechargeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			
			//计算订单总金额
			double amount = order.getDouble("amount");
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flagStr);
			
			if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
				//1：微信支付
				//获取客户端IP
				String remoteip = CommonKit.getClientIp(getRequest());
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			
				//向微信发起预支付请求
				PreOrderReqData preOrderReqData = new PreOrderReqData("亿品直供",orderNum,amountStr,remoteip,PropKit.get("weixinpay.goodsOrderNotifyUrl"),startDate,expireDate);
				PreOrderResData preOrderRspData = null;
				try {
					preOrderRspData = (PreOrderResData)UtilKit.getObjectFromXML(new HttpsRequest().post(PropKit.get("weixinpay.unifiedorder"), preOrderReqData), PreOrderResData.class);
				}catch(Exception e){
					logger.info(">>>>>>>>>>>>>>>我信支付错误");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
				}
				//预支付完成
				if(preOrderRspData!=null){
					System.out.println("Response....:"+preOrderReqData);
					//保存接口请求记录
					String sendContent = UtilKit.getXMLFromObject(preOrderReqData);
					String returnContent = UtilKit.getXMLFromObject(preOrderRspData);
					new OrderPayAPIRecord().set("orderNum", orderNum)
						.set("sendContent", sendContent)
						.set("returnContent", returnContent)
						.set("payMethod", payMethod)
						.set("flag", 1)
						.save();
					if(preOrderRspData.getReturn_code().equals("SUCCESS")&&preOrderRspData.getResult_code().equals("SUCCESS")){
						//更新订单支付方式为微信
						order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
						//向客户端返回结果
						String noncestr = CommonKit.getRandomStringByLength(32);
						String timestamp = DatetimeKit.getTimestamp();
						String url = PropKit.get("weixinpay.redirect_url");
						url = "http://api.nczywc.cn/h5/#/pages/money/paySuccess";
						try {
							url = URLEncoder.encode(url, "GBK");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							renderFailed("编码转换错误");
				    		return;
						}
						url = preOrderRspData.getMweb_url()+ "&redirect_url=" +url + "?ORDERNUM="+orderNum ;
						renderSuccess(ResultMap.newInstance()
								.put("APPID", preOrderReqData.getAppid())
								.put("PARTNERID", preOrderReqData.getMch_id())
								.put("PREPAYID", preOrderRspData.getPrepay_id())
								.put("URL",url)
								.put("PACKAGE", "Sign=WXPay")
								.put("NONCESTR", noncestr)
								.put("TIMESTAMP", timestamp)
								.put("SIGN", Signature.getSign(ResultMap.newInstance()
										.put("appid", preOrderReqData.getAppid())
										.put("partnerid", preOrderReqData.getMch_id())
										.put("prepayid", preOrderRspData.getPrepay_id())
										.put("package", "Sign=WXPay")
										.put("noncestr", noncestr)
										.put("timestamp", timestamp).getAttrs())));
						return;
					}
				}
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
				System.out.println("H5进入支付宝支付");
				//2：支付宝支付
				//获取订单总金额，并转换为以“元”为单位
				String amountStr1 = String.valueOf(Double.valueOf(amount)).toString();
				String gateway=PropKit.get("applipay.url");
				String app_id=PropKit.get("appalipay.partner");
				String privateKey=PropKit.get("appalipay.privateKey");
				String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
				String charset=PropKit.get("applipay.charset");
				String sign_type=PropKit.get("applipay.signType");
				String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
				String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
				String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
				String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
				String alipay_return_url =PropKit.get("appalipay.returnUrl");
				
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				
				
				
				
				AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
				model.setOutTradeNo(orderNum);
				model.setTotalAmount(amountStr1);
				model.setSubject("亿拼惠充值订单");
				model.setProductCode("QUICK_WAP_WAY");
				
				AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
				alipayRequest.setBizModel(model);
				alipayRequest.setNotifyUrl(alipay_notify_url);
				alipayRequest.setReturnUrl(alipay_return_url);
				
				DefaultAlipayClient alipayClient;
				try {
					alipayClient = new DefaultAlipayClient(certAlipayRequest);
					AlipayTradeWapPayResponse response= alipayClient.pageExecute(alipayRequest);
					
					new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", alipayRequest.getBizModel().toString())
					.set("returnContent", response.getBody())
					.set("payMethod", payMethod)
					.set("flag", 1)
					.save();
					//更新订单支付方式为支付宝
					order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
					//将结果返回给客户端
					renderSuccess(ResultMap.newInstance().put("URL", response.getBody()).getAttrs());
					return;
				} catch (AlipayApiException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					renderFailed("支付宝支付错误");
					return;
				}
				
			}else if(payMethod == OrderCode.OrderPayMethod.BALANCE){
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE).update();
				//查询用户余额  判断是否充足
				Map<String,String> map = new HashMap<String,String>();
				map.put("token", token);
				JSONObject js = ZYPay.find(map);
				Map<String, Object> resMap =EncryUtils.toMap(js);
				if("000000".equals(resMap.get("result"))){
		    		//查询成功
					JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
					JSONArray array = JSONArray.fromObject(jsondata.get("DATA"));
					jsondata = JSONObject.fromObject(array.get(0));
					if(service.saveMoneyUp(jsondata.getDouble("SUMMONEY"),getCurrentUser().getInt("id"))!=1){
			    		renderFailed("网络错误，请稍后重试");
			    		return;
					}
		    		//账户余额
					Double money = jsondata.getDouble("SUMMONEY");
					if(Double.compare(money, amount)==-1){
//						余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					User user = service.findUserByid(getCurrentUser().getInt("id"));
					Map<String,String> map1 = new HashMap<String,String>();
					String orderid = "Z"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(4);
					map1.put("order_type", PayCode.ORDERTYPE.MONEYPAY);//下单类型 2在线支付
					map1.put("order_id", orderid);
					map1.put("pay_firmid", user.get("payid")+"");
					map1.put("pay_firmname", user.get("name"));
					map1.put("pay_phone", user.get("phone"));
					String isPC = EncryUtils.JudgeIsMoblie(getRequest());
					map1.put("terminal_type", isPC);
					if("1".equals(isPC)){
						map1.put("terminal_num","MAC");
					}else if("2".equals(isPC)){
						map1.put("terminal_num","IMEI");
					}else{
						map1.put("terminal_num","OTHER");
					}
					String ip = EncryUtils.getRealIp(getRequest());
					map1.put("order_ip", ip);
					String money1 = new DecimalFormat("0.00").format(amount);
					map1.put("order_money",money1);
					Double orderfree =0.00;
					String format = new DecimalFormat("0.00").format(orderfree);
					map1.put("order_fee",format);
					map1.put("token",token);
					JSONObject jss = null;
					try {
						jss =ZYPay.createOrder(map1);
					} catch (Exception e) {
						renderFailed("Base64转换失败");
						return;
					}
					Map<String, Object> resMap1 =EncryUtils.toMap(jss);
					if("000000".equals(resMap1.get("result"))){
			    		//支付
						JSONObject jsondata1 = JSONObject.fromObject(resMap1.get("data"));
						if(Db.findFirst("SELECT * FROM t_bus_user_pay_orderid WHERE ischeck=1 AND fromOrderNum=?",orderNum)!=null){
							renderFailed("订单重复提交");
							return;
						}
						//创建订单表
						Record re = new Record().set("orderid",orderid)
												.set("fromOrderNum", orderNum)
												.set("userid", user.getInt("id"))
												.set("type", 1)
												.set("ischeck", 0)
												.set("money", money1)
												.set("moneyfree", format)
												.set("createDate", new Date());
						if(!Db.save("t_bus_user_pay_orderid", re)){
							logger.info(">>>>>>>>>>>>>>>纪录保存失败");
				    		renderFailed("网络错误，请稍后重试");
							return;
						}
			    		renderSuccess(jsondata1.get("location_url"));
			    		return;
			    	}else{
			    		//支付失败
			    		renderFailed((String)resMap1.get("msg"));
			    		return;
			    	}
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
			logger.info(">>>>>>>>>>>>>>>暂时没有该支付方式");
    		renderFailed("网络错误，请稍后重试");
			return;
			
		}
	}
	
	/**
	 * 查询指定订单支付结果<br/>
	 * 客户端跳转向微信或其他第三方支付平台，在支付完成后，第三方平台会返回客户端界面，并告知支付结果，此时客户端需要再次向服务端发起支付结果查询请求
	 * @param ORDERNUM 订单号
	 * @param PAYSTATE 支付结果，1:已支付，0:未支付
	 */
	public void query(){
		String orderNum = getPara("ORDERNUM");
		System.out.println("查询订单号:"+orderNum);
		String token = getPara("TOKENP");
		if(StrKit.isBlank(orderNum)||"undefined".equals(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(token)){
			renderFailed("参数TOKENP不能为空");
    		return;
		}
		//支付宝
		String gateway=PropKit.get("applipay.url");
		String app_id=PropKit.get("appalipay.partner");
		String privateKey=PropKit.get("appalipay.privateKey");
		String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
		String charset=PropKit.get("applipay.charset");
		String sign_type=PropKit.get("applipay.signType");
		String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
		String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
		String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
		String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
		
		
		String str1 = orderNum.subSequence(0, 1).toString();
		
		if("G".equals(str1)){
			
			//查询订单列表，并验证订单是否存在，以及订单支付状态
			Order order = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//依次判断订单支付状态
			if(order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
				System.out.println("查询到订单未支付，订单支付方式"+order.getInt("paytype"));
				//如果状态为未支付，则调用相应支付平台的接口进行再次验证
				if(order.getInt("paytype")==OrderCode.OrderPayMethod.WEIXIN){
					System.out.println("查询到订单未支付进入微信");
					//1：微信支付
					try {
						QueryOrderReqData queryOrderReqData = new QueryOrderReqData(orderNum);
						String responseStr = new HttpsRequest().post(PropKit.get("weixinpay.orderquery"), queryOrderReqData);
						QueryOrderResData queryOrderResData = (QueryOrderResData) UtilKit.getObjectFromXML(responseStr, QueryOrderResData.class);
						if(queryOrderResData!=null){
							//保存接口请求记录
							new OrderPayAPIRecord().set("orderNum", orderNum)
							.set("sendContent", UtilKit.getXMLFromObject(queryOrderReqData))
							.set("returnContent", UtilKit.getXMLFromObject(queryOrderResData))
							.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
							.set("flag", 3)
							.save();
							if(queryOrderResData.getReturn_code().equals("SUCCESS")&&queryOrderResData.getResult_code().equals("SUCCESS")&&queryOrderResData.getTrade_state().equals("SUCCESS")){
								// 微信订单状态的更改  
								try {
									// 
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"微信支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.WEIXIN);
								} catch (Exception e) {
									e.printStackTrace();
									logger.info(">>>>>>>>>>>>>>>状态，积分表更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
								renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
								return;
							}else{
								renderFailed("2");  
					    		return;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.ALIPAY){
					System.out.println("查询到订单未支付进入支付宝");
					//构造client
					CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
					certAlipayRequest.setServerUrl(gateway);
					certAlipayRequest.setAppId(app_id);
					certAlipayRequest.setPrivateKey(privateKey);
					certAlipayRequest.setFormat("json");
					certAlipayRequest.setCharset(charset);
					certAlipayRequest.setSignType(sign_type);
					certAlipayRequest.setCertPath(app_cert_path);
					certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
					certAlipayRequest.setRootCertPath(alipay_root_cert_path);
					AlipayClient alipayClient;
					try {
						alipayClient = new DefaultAlipayClient(certAlipayRequest);
						AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
						request.setBizContent("{" +
						"   \"out_trade_no\":\""
						+ orderNum
						+ "\"" +
						"  }");//设置业务参数
						AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
						System.out.println(response.getBody());
						//根据response中的结果继续业务逻辑处理
						if(response.isSuccess()){
							if ("TRADE_SUCCESS".equals(response.getTradeStatus())||"TRADE_FINISHED".equals(response.getTradeStatus())) {
								try {
									// 支付宝订单状态的更改  
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"支付宝支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.ALIPAY);
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
									return;
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>支付宝积分，惠券更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
							}
						}else {
							logger.info("支付宝查询失败");
				    		renderFailed("网络错误，请稍后重试");
							return;
						}
						
					} catch (AlipayApiException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						logger.info("支付宝查询失败");
			    		renderFailed("网络错误，请稍后重试");
						return;
					}
					//2：支付宝支付不提供相应的查询状态功能，以数据库订单状态为准
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.SEL){
					//查询支付结果
					Map<String,String> dataMap = new HashMap<String,String>();
					dataMap.put("merOrderNo", orderNum);
					String str = null;
					try {
						Map<String, String> queryPay = SQpay.queryPay(dataMap);
						//查询成功并且已结算状态
						if("查询成功".equals(queryPay.get("message"))&&"1".equals(queryPay.get("State"))){
							//已经结算
							// 支付宝订单状态的更改 
							try {
								service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"银联支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.SEL);
							} catch (Exception e) {
								logger.info(">>>>>>>>>>>>>>>支付状态，积分更新失败");
								e.printStackTrace();
					    		renderFailed("网络错误，请稍后重试");
								return;
							}
						}else{
							renderFailed("未结算订单，支付失败");
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
						renderFailed("查询支付结果失败");
						return;
					}
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.BALANCE){
					
					
					//根据orderNum 查找orderid 
					List<Record> res = service.queryOrderByOrderNum(orderNum);
					if(res==null|| res.size()<=0){
						renderFailed("没有该笔订单");
						return;
					}
					for(Record re : res){
						Map<String,String> map = new HashMap<String,String>();
						map.put("order_id", re.getStr("orderid"));
						System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>订单号"+re.getStr("orderid"));
						map.put("token", token);
						JSONObject js = ZYPay.orderstate(map);
						Map<String, Object> resMap =EncryUtils.toMap(js);
						if("000000".equals(resMap.get("result"))){
				    		//查询成功
							JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
							if(jsondata.get("order_type").equals("2")&&jsondata.get("order_status").equals("S")){
								// 1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
								int count = 0;
								try {
									count = service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"余额支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.BALANCE);
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>更新记录失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
						    		return;
								}
								System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>1111支付结果"+count);
								if(count == 1){
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
									return;
								}
							}
				    	}
					}
				}else {
					renderFailed("0");  
		    		return;
				}
			}else if(order.getInt("payState")==OrderCode.OrderPayState.HAD_PAY){
				System.out.println("查询订单已支付");
					int count = 0;
					try {
						count = service.UpdateOrderStock(order,getCurrentUser());
					} catch (Exception e) {
						logger.info(">>>>>>>>>>>>>>>更新记录失败");
						e.printStackTrace();
			    		renderFailed("网络错误，请稍后重试");
			    		return;
					}
					System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>1111支付结果"+count);
					if(count == 1){
						renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
						return;
					}
				
				
				
			}
    		renderFailed("2");  
    		return;
			
		}else if("D".equals(str1)){
			//查询订单列表，并验证订单是否存在，以及订单支付状态 
			
			OrderE order = service.getExchangeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			
			
			System.out.println("LLLLLLLLLLLLLLLLLLLLLLLL"+order.getInt("payState"));
			
			//依次判断订单支付状态
			if(order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
				//如果状态为未支付，则调用相应支付平台的接口进行再次验证
				if(order.getInt("paytype")==OrderCode.OrderPayMethod.WEIXIN){
					//1：微信支付
					try {
						QueryOrderReqData queryOrderReqData = new QueryOrderReqData(orderNum);
						String responseStr = new HttpsRequest().post(PropKit.get("weixinpay.orderquery"), queryOrderReqData);
						QueryOrderResData queryOrderResData = (QueryOrderResData) UtilKit.getObjectFromXML(responseStr, QueryOrderResData.class);
						if(queryOrderResData!=null){
							//保存接口请求记录
							new OrderPayAPIRecord().set("orderNum", orderNum)
							.set("sendContent", UtilKit.getXMLFromObject(queryOrderReqData))
							.set("returnContent", UtilKit.getXMLFromObject(queryOrderResData))
							.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
							.set("flag", 3)
							.save();
							if(queryOrderResData.getReturn_code().equals("SUCCESS")&&queryOrderResData.getResult_code().equals("SUCCESS")&&queryOrderResData.getTrade_state().equals("SUCCESS")){
								// 微信订单状态的更改  积分等券的发放
								try {
									// 
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"微信支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.WEIXIN);
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>状态，积分表更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
								renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
								return;
							}else{
								renderFailed("2");  
					    		return;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.ALIPAY){
					System.out.println("查询到订单未支付进入支付宝");
					//构造client
					CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
					certAlipayRequest.setServerUrl(gateway);
					certAlipayRequest.setAppId(app_id);
					certAlipayRequest.setPrivateKey(privateKey);
					certAlipayRequest.setFormat("json");
					certAlipayRequest.setCharset(charset);
					certAlipayRequest.setSignType(sign_type);
					certAlipayRequest.setCertPath(app_cert_path);
					certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
					certAlipayRequest.setRootCertPath(alipay_root_cert_path);
					AlipayClient alipayClient;
					try {
						alipayClient = new DefaultAlipayClient(certAlipayRequest);
						AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
						request.setBizContent("{" +
						"   \"out_trade_no\":\""
						+ orderNum
						+ "\"" +
						"  }");//设置业务参数
						AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
						System.out.println(response.getBody());
						//根据response中的结果继续业务逻辑处理
						if(response.isSuccess()){
							if ("TRADE_SUCCESS".equals(response.getTradeStatus())||"TRADE_FINISHED".equals(response.getTradeStatus())) {
								try {
									// 支付宝订单状态的更改  积分等券的发放
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"支付宝支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.ALIPAY);
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
									return;
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>支付宝积分，惠券更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
							}
						}else {
							logger.info("支付宝查询失败");
				    		renderFailed("网络错误，请稍后重试");
							return;
						}
						
					} catch (AlipayApiException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						logger.info("支付宝查询失败");
			    		renderFailed("网络错误，请稍后重试");
						return;
					}
					//2：支付宝支付不提供相应的查询状态功能，以数据库订单状态为准
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.BALANCE){
					//根据orderNum 查找orderid  
					List<Record> res = service.queryOrderByOrderNum(orderNum);
					if(res==null|| res.size()<=0){
						renderFailed("没有该笔订单");
						return;
					}
					for(Record re : res){
						Map<String,String> map = new HashMap<String,String>();
						map.put("order_id", re.getStr("orderid"));
						map.put("token", token);
						JSONObject js = ZYPay.orderstate(map);
						Map<String, Object> resMap =EncryUtils.toMap(js);
						if("000000".equals(resMap.get("result"))){
				    		//查询成功
							JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
							if(jsondata.get("order_type").equals("2")&&jsondata.get("order_status").equals("S")){
								int count = 0;
								// 1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
								try {
									count = service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"余额支付","支付完成，等待商家发货",OrderCode.OrderPayTypes.BALANCE);
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>更新支付状态，积分表失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
						    		return;
								}
								if(count == 1){
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
									return;
								}
							}
				    	}
					}
					
				}else {
					renderFailed("0");  
		    		return;
				}
			}else if(order.getInt("payState")==OrderCode.OrderPayState.HAD_PAY){
				System.out.println("兑换订单支付查询订单已支付");
					try {
						User user = getCurrentUser();
						service.monryQuery(order, user);
						renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
						return;
					} catch (Exception e) {
						logger.info(">>>>>>>>>>>>>>>更新支付状态，积分表失败");
						e.printStackTrace();
			    		renderFailed("网络错误，请稍后重试");
			    		return;
					}
				
			}
			renderFailed("2");  
    		return;
		}else if("Z".equals(str1)){
			//查询订单列表，并验证订单是否存在，以及订单支付状态 
			
			OrderZ order = service.getRechargeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//依次判断订单支付状态
			if(order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
				//如果状态为未支付，则调用相应支付平台的接口进行再次验证
				if(order.getInt("paytype")==OrderCode.OrderPayMethod.WEIXIN){
					//1：微信支付
					try {
						QueryOrderReqData queryOrderReqData = new QueryOrderReqData(orderNum);
						String responseStr = new HttpsRequest().post(PropKit.get("weixinpay.orderquery"), queryOrderReqData);
						QueryOrderResData queryOrderResData = (QueryOrderResData) UtilKit.getObjectFromXML(responseStr, QueryOrderResData.class);
						if(queryOrderResData!=null){
							//保存接口请求记录
							new OrderPayAPIRecord().set("orderNum", orderNum)
							.set("sendContent", UtilKit.getXMLFromObject(queryOrderReqData))
							.set("returnContent", UtilKit.getXMLFromObject(queryOrderResData))
							.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
							.set("flag", 3)
							.save();
							if(queryOrderResData.getReturn_code().equals("SUCCESS")&&queryOrderResData.getResult_code().equals("SUCCESS")&&queryOrderResData.getTrade_state().equals("SUCCESS")){
								// 微信订单状态的更改  积分等券的发放
								try {
									// 
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"微信支付","支付完成，等待商家发货",1,"充值奖励",OrderCode.OrderPayTypes.WEIXIN);
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>状态，积分表更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
								renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
								return;
							}else{
								renderFailed("2");  
					    		return;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.ALIPAY){
					System.out.println("查询到订单未支付进入支付宝");
					//构造client
					CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
					certAlipayRequest.setServerUrl(gateway);
					certAlipayRequest.setAppId(app_id);
					certAlipayRequest.setPrivateKey(privateKey);
					certAlipayRequest.setFormat("json");
					certAlipayRequest.setCharset(charset);
					certAlipayRequest.setSignType(sign_type);
					certAlipayRequest.setCertPath(app_cert_path);
					certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
					certAlipayRequest.setRootCertPath(alipay_root_cert_path);
					AlipayClient alipayClient;
					try {
						alipayClient = new DefaultAlipayClient(certAlipayRequest);
						AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
						request.setBizContent("{" +
						"   \"out_trade_no\":\""
						+ orderNum
						+ "\"" +
						"  }");//设置业务参数
						AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
						System.out.println(response.getBody());
						//根据response中的结果继续业务逻辑处理
						if(response.isSuccess()){
							if ("TRADE_SUCCESS".equals(response.getTradeStatus())||"TRADE_FINISHED".equals(response.getTradeStatus())) {
								try {
									// 支付宝订单状态的更改  积分等券的发放
									service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"支付宝支付","支付完成，等待商家发货",1,"充值奖励",OrderCode.OrderPayTypes.ALIPAY);
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());
									return;
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>支付宝积分，惠券更新失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
									return;
								}
							}
						}else {
							logger.info("支付宝查询失败");
				    		renderFailed("网络错误，请稍后重试");
							return;
						}
						
					} catch (AlipayApiException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						logger.info("支付宝查询失败");
			    		renderFailed("网络错误，请稍后重试");
						return;
					}
					//2：支付宝支付不提供相应的查询状态功能，以数据库订单状态为准
				}else if(order.getInt("paytype")==OrderCode.OrderPayMethod.BALANCE){
					//根据orderNum 查找orderid  
					List<Record> res = service.queryOrderByOrderNum(orderNum);
					if(res==null|| res.size()<=0){
						renderFailed("没有该笔订单");
						return;
					}
					for(Record re : res){
						Map<String,String> map = new HashMap<String,String>();
						map.put("order_id", re.getStr("orderid"));
						map.put("token", token);
						JSONObject js = ZYPay.orderstate(map);
						Map<String, Object> resMap =EncryUtils.toMap(js);
						if("000000".equals(resMap.get("result"))){
				    		//查询成功
							JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
							if(jsondata.get("order_type").equals("2")&&jsondata.get("order_status").equals("S")){
								int count = 0;
								// 1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
								try {
									count = service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),"余额支付","支付完成，等待商家发货",1,"充值奖励",OrderCode.OrderPayTypes.BALANCE);
								} catch (Exception e) {
									logger.info(">>>>>>>>>>>>>>>更新支付状态，积分表失败");
									e.printStackTrace();
						    		renderFailed("网络错误，请稍后重试");
						    		return;
								}
								if(count == 1){
									renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
									return;
								}
							}
				    	}
					}
				}else {
					renderFailed("0");  
		    		return;
				}
			}else if(order.getInt("payState")==OrderCode.OrderPayState.HAD_PAY){
				System.out.println("兑换订单支付查询订单已支付");
					int count = 0;
					try {
						count = service.orderMoneyStateUpdateAndGive(order,getCurrentUser(),1,"充值奖励");
					} catch (Exception e) {
						logger.info(">>>>>>>>>>>>>>>更新支付状态，积分表失败");
						e.printStackTrace();
			    		renderFailed("网络错误，请稍后重试");
			    		return;
					}
					System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>1111支付结果"+count);
					if(count == 1){
						renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1).getAttrs());  
						return;
					}
				
			}
			renderFailed("2");  
    		return;
		}
		
	}
	
	/**
	 * 查询订单列表
	 * @param APIVERSION 服务端接口版本号，以此判断来兼容旧版本接口
	 * @param FLAG 订单状态，0：全部，1:待付款，2：待收货，3：待评价  4：待分享，
	 */
	public void list(){
		//获取订单状态
		int flag = getParaToInt("FLAG");
		int id = getCurrentUser().getInt("id");
		//查询普通订单
		List<Record> pages = service.findByFlag(id,flag);
		//查询兑换订单
		List<Record> pagesExchange = service.findExchangeOrderByFlag(id,flag);
		
		
		if(pagesExchange !=null && pagesExchange.size()>0){
			//根据id查找
			for(Record r : pagesExchange){
				List<Record> findExchangeByid = service.findExchangeByid(r.getInt("goodsid"),r.getInt("specsid"));
				r.set("list", findExchangeByid);
				r.set("exchange", "1");
			}
			pages.addAll(pagesExchange);
		}
		
		if(pages !=null && pages.size()>0){
			for(Record page : pages){
				List<Record> lists = service.findListByNum(page.get("orderNum"));
				page.set("list", lists);
			}
		}
		//查询团购订单
		List<Record> pagesGroup = service.findGroupOrderByFlag(id,flag);
		
		if(pagesGroup!=null && pagesGroup.size()>0){
			for(Record re : pagesGroup){
				Goods good = Goods.me().findById(re.getInt("goodsid"));
				List<Goods> list = new ArrayList<Goods>();
				list.add(good);
				re.set("list", list);
				re.set("group", "1");
			}
		}
		if (pages != null ){
			pages.addAll(pagesGroup);
		} else {
			pages = pagesGroup;
		}
		
		for(Record re : pages){
			if(re.getInt("orderState")==OrderCode.OrderState.NORMAL){
				long thistime = re.getTimestamp("expireDate").getTime();
				long newtime = new Date().getTime();
				if(thistime<newtime){
					re.set("orderState", 9);
				}
			}
		}
		
		Collections.sort(pages,new Comparator<Record>(){

			@Override
			public int compare(Record u1, Record u2) {
				long time1 = DatetimeKit.StrToDate(u1.getTimestamp("startDateTime").toString()).getTime();
				long time2 = DatetimeKit.StrToDate(u2.getTimestamp("startDateTime").toString()).getTime();
				long compare = time1-time2;
				if ( compare>0 ){
					return -1;
				} else {
					return 1;
				}
			}
			
		});
		
		renderSuccess(pages);
	}
	
	/**
	 * 查询订单数量
	 */
	public void findOrderNum() {
		List<Record> orderNum=service.findOrderNum(getCurrentUser().getInt("id"));
		if (orderNum ==null || orderNum.size()==0) {
			renderSuccess("查询普通订单数量失败");
		}
		
		List<Record> exchangeOrderNum=service.findExchangeOrderNum(getCurrentUser().getInt("id"));
		if (exchangeOrderNum !=null || exchangeOrderNum.size()!=0) {
			orderNum.addAll(exchangeOrderNum);
		}
		List<Record> groupBuyOrderNum=service.findGroupBuyOrderNum(getCurrentUser().getInt("id"));
		if (groupBuyOrderNum !=null || groupBuyOrderNum.size()!=0) {
			orderNum.addAll(groupBuyOrderNum);
		}
		renderSuccess(orderNum);
	}
	
	/**
	 * 查询团购订单待分享数量
	 */
	public void findOrderNumShare() {
		Record orderNum=service.findOrderNumShare(getCurrentUser().getInt("id"));
		renderSuccess(orderNum);
	}
	
	
	/**
	 * 查询退款订单列表
	 */
	public void refund() {
		int pageNum = getParaToInt("pageNum",1);
		String storeid = getPara("STOREID");
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		Page<Record> page = service.findRefundByPage(Integer.valueOf(storeid), getCurrentUser().getInt("id"), pageNum, pageSize);
		if(page!=null){
			//查询订单的商品列表供页面展示
			service.getOrderGoodsList(page.getList());
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", page.getList())
					.put("STATEMENT", PropKit.get("constants.refund.statement")));
		}
		return;
	}
	
	/**
	 * 取消订单
	 * @param ORDERNUM 订单号
	 * @param REASON 取消订单理由
	 * @param ISREDEEM   0 普通订单取消  1 兑换订单取消  2 团购取消订单
	 */
	public void cancel(){
		String orderNum = getPara("ORDERNUM");
		String isRedeem = getPara("ISREDEEM");
		String reason = getPara("REASON");
		String isSpike = getPara("ISSPIKE");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(isRedeem)){
			renderFailed("参数ISREDEEM不能为空");
    		return;
		}else if(StrKit.isBlank(reason)){
			renderFailed("参数REASON不能为空");
    		return;
		}else if(StrKit.isBlank(isSpike)){
			renderFailed("参数ISSPIKE不能为空");
    		return;
		}else{
			if("1".equals(isRedeem)){
				//兑换订单 
				OrderE order = service.getExchangeOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(order!=null){
					//2.根据订单不同状态进行不同操作
					int payType = order.getInt("payType");
					int payState = order.getInt("payState");
					try {
						//在service中进行取消订单(修改订单状态、生成退款订单)的一系列操作,保证事务回滚
						service.cancelExchangeOrder(order,reason,payType,payState,orderNum);
						renderSuccess(order);
						return;
					} catch (Exception e) {
						e.printStackTrace();
					}
					//3.其他情况
					renderFailed("取消订单失败");
					return;
				}else{
					renderFailed("订单不存在！");
					return;
				}
				
			}else if("0".equals(isRedeem)){
				Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(order!=null){
					//2.根据订单不同状态进行不同操作
					int payType = order.getInt("payType");
					int payState = order.getInt("payState");
					try {
						//在service中进行取消订单(修改订单状态、生成退款订单)的一系列操作,保证事务回滚
						service.cancelOrder(order,reason,payType,payState,orderNum,isSpike);
						renderSuccess(order);
						return;
					} catch (Exception e) {
						e.printStackTrace();
					}
					//3.其他情况
					renderFailed("取消订单失败");
					return;
				}else{
					renderFailed("订单不存在！");
					return;
				}
			}else{
				//团购订单  
				try {
					groupService.cannlGroup(orderNum,reason,getCurrentUser().getInt("id"));
					renderSuccess("取消成功");
				} catch (Exception e) {
					renderFailed(e.getMessage());
				}
			}
			
		}
	}
	
	/**
	 * 删除订单
	 * @param ORDERNUM 订单号
	 * @param ISREDEEM 0 普通订单  1 兑换订单 2 团购订单
	 */
	public void delete(){
		String orderNum = getPara("ORDERNUM");
		String isRedeem = getPara("ISREDEEM");
		int id = getCurrentUser().getInt("id");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(isRedeem)){
			renderFailed("参数ISREDEEM不能为空");
    		return;
		}else{
			try {
				service.delete(orderNum,isRedeem,id);
				renderSuccess("成功");
			} catch (Exception e) {
				renderFailed(e.getMessage());
			}
			
		}
	}

	/**
	 * 签收
	 * @param ORDERNUM 订单号
	 * @param ISREDEEM  是否使用优惠券    0 纯现金支付，1兑换  2团购
	 */
	public void receive(){
		String orderNum = getPara("ORDERNUM");
		String isRedeem = getPara("ISREDEEM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(isRedeem)){
			renderFailed("参数ISREDEEM不能为空");
    		return;
		}else{
			if("1".equals(isRedeem)){
				//兑换订单
				OrderE order = service.getExchangeOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(order!=null){
					//1.判断订单状态是否为“正常”状态
					int orderState = order.getInt("orderState");
					if(orderState!=OrderCode.OrderState.SHOU){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
					//2.根据订单不同状态进行不同操作
					int payType = order.getInt("payType");
					int payState = order.getInt("payState");
					//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“已发货”时可签收订单
					if(payType!=OrderCode.OrderPayType.ON_DELIVERY){
						if(payState!=OrderCode.OrderPayState.HAD_PAY){
							renderFailed("此订单当前不允许签收");
				    		return;
						}
					}
					//3.签收订单操作，并记录日志
					try {
						//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
						service.receiveExchangeOrder(order,getCurrentUser());
						renderSuccess();
						return;
					} catch (Exception e) {
						renderFailed("签收订单失败了");
						e.printStackTrace();
					}
					//4.其他情况
					renderFailed("签收订单失败");
					return;
				}else{
					renderFailed("订单不存在！");
					return;
				}
				
			}else if("0".equals(isRedeem)){
				Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(order!=null){
					//1.判断订单状态是否为“正常”状态
					int orderState = order.getInt("orderState");
					if(orderState!=OrderCode.OrderState.SHOU){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
					//2.根据订单不同状态进行不同操作
					int payType = order.getInt("payType");
					int payState = order.getInt("payState");
					//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“已发货”时可签收订单
					if(payType!=OrderCode.OrderPayType.ON_DELIVERY){
						if(payState!=OrderCode.OrderPayState.HAD_PAY){
							renderFailed("此订单当前不允许签收");
				    		return;
						}
					}
					//3.签收订单操作，并记录日志
					try {
						//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
						service.receiveOrder(order,getCurrentUser());
						renderSuccess();
						return;
					} catch (Exception e) {
						renderFailed("签收订单失败了");
						e.printStackTrace();
					}
					//4.其他情况
					renderFailed("签收订单失败");
					return;
				}else{
					renderFailed("订单不存在！");
					return;
				}
			}else if("2".equals(isRedeem)){
				//团购-1 订单不存在 1签收成功 2签收失败
				int count = service.receiveOrderG(getCurrentUser(),orderNum);
				if ( count == -1 ){
					renderFailed("订单不存在！");
				} else if(count == 2 ){
					renderFailed("签收失败！请稍后重试");
				} else {
					renderSuccess();
				}
			}
			 
			
		}
	}

	/**
	 * 用户催单
	 * @param ORDERNUM 订单号
	 */
	public void urge(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许催单");
		    		return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“未发货”时可催单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(payState!=OrderCode.OrderPayState.HAD_PAY&&deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许催单");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，不允许催单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					renderFailed("此订单当前不允许催单");
		    		return;
				}else
				//2.3.货到付款+送货上门时，发货状态为“未发货”时可催单订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许催单");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，不允许催单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					renderFailed("此订单当前不允许催单");
		    		return;
				}
				//3.催单操作
				int urgeTimes = order.getInt("urgeTimes");
				if(urgeTimes==0){
					//首次催单需要在下单xx分钟后
					Date orderDate = order.getDate("createDate");
					Date now = new Date();
					int diffMin = (int)(now.getTime()-orderDate.getTime())/(1000*60);
					if(diffMin<=PropKit.getInt("constants.order.urgeFirstTime")){
						renderFailed("您的订单正在加急处理中，请耐心等待");
						return;
					}
				}else{
					//第二次以后催单，间隔需要大于xx分钟
					Date urgeLastTimeDate = order.getDate("urgeLastTime");
					Date now = new Date();
					int diffMin = (int)(now.getTime()-urgeLastTimeDate.getTime())/(1000*60);
					if(diffMin<=PropKit.getInt("constants.order.urgePerTime")){
						renderFailed("您的订单正在加急处理中，请耐心等待");
						return;
					}
				}
				try {
					//催单，修改催单累计次数加1，更新最后一次催单记录时间
					order = service.urgeOrder(getCurrentUser().getInt("id"),orderNum);
					urgeTimes = order.getInt("urgeTimes");
					String urgeLastTime = DatetimeKit.getFormatDate(order.getDate("urgeLastTime"),"yyyy-MM-dd HH:mm:ss");
					//记录日志
					service.log(orderNum,OrderCode.OrderLogType.URGE,"用户",OrderCode.OrderLogType.URGE_ACTION,"第"+order.getInt("urgeTimes")+"次催单，催单时间："+urgeLastTime);
					//返回客户端
					renderSuccess(ResultMap.newInstance().put("TIMES", urgeTimes).put("DATETIME", urgeLastTime));
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}

				//4.其他情况
				renderFailed("催单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 查询订单详情，及订单商品列表<br/>
	 * 注意，查询订单时，只查询订单状态“正常”、“已完成”、“已取消”的
	 * @param ORDERNUM 订单号
	 * @param ISREDEEM  0 纯现金支付，1兑换  2团购
	 */
	public void detail(){
		String orderNum = getPara("ORDERNUM");
		String isRedeem = getPara("ISREDEEM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(isRedeem)){
			renderFailed("参数ISREDEEM不能为空");
    		return;
		}{
			if("0".equals(isRedeem)){
				Order orders = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(orders!=null){
					Order order = service.getAddressByid(orders);
					//查询订单的商品清单列表
					order.put("GOODSLIST", service.getGoodsListByOrderNum(orderNum));
					//判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
					if(order.getInt("orderState")==OrderCode.OrderState.NORMAL&&order.getInt("PAYSTATE")==OrderCode.OrderPayState.NO_PAY){
						long endTimestamp = order.getTimestamp("expireDate").getTime();
						long nowTimestamp = System.currentTimeMillis();
						//判断从当前时间到过期时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果大于0，则将该数字回传给客户端
						if(endTimestamp-(nowTimestamp+5*1000)>0){
							//计算出离过期还剩余的毫秒数返回给客户端
							order.put("REMAIN",endTimestamp-(nowTimestamp+5*1000));
						}else{
							//相反，则认为订单已过期，修改订单状态返回给客户端
							order.set("ORDERSTATE", OrderCode.OrderState.LATER);
						}
					}
					renderSuccess(order);
					return;
				}else{
					renderFailed("此订单不存在");
					return;
				}
			}else if("1".equals(isRedeem)){
				OrderE orders = service.getExchangeOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(orders!=null){
					OrderE order = service.getExchangeAddressByid(orders);
					//查询订单的商品清单列表
					order.put("GOODSLIST", service.getExchanegByOrderNum(orderNum));
					//判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
					if(order.getInt("orderState")==OrderCode.OrderState.NORMAL&&order.getInt("PAYSTATE")==OrderCode.OrderPayState.NO_PAY){
						long endTimestamp = order.getTimestamp("expireDate").getTime();
						long nowTimestamp = System.currentTimeMillis();
						//判断从当前时间到过期时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果大于0，则将该数字回传给客户端
						if(endTimestamp-(nowTimestamp+5*1000)>0){
							//计算出离过期还剩余的毫秒数返回给客户端
							order.put("REMAIN",endTimestamp-(nowTimestamp+5*1000));
						}else{
							//相反，则认为订单已过期，修改订单状态返回给客户端
							order.set("ORDERSTATE", OrderCode.OrderState.LATER);
						}
					}
					renderSuccess(order);
					return;
				}else{
					renderFailed("此订单不存在");
					return;
				}
			}else{
				//团购
				OrderG orders = service.getGroupOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
				if(orders!=null){
					OrderG order = service.getGroupAddressByid(orders);
					//查询订单的商品清单列表
					order.put("GOODSLIST", Goods.me().find("SELECT * FROM t_bus_goods WHERE id =? ", order.getInt("goodsid")));
					//判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
					if(order.getInt("orderState")==OrderCode.OrderState.NORMAL&&order.getInt("PAYSTATE")==OrderCode.OrderPayState.NO_PAY){
						long endTimestamp = order.getTimestamp("expireDate").getTime();
						long nowTimestamp = System.currentTimeMillis();
						//判断从当前时间到过期时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果大于0，则将该数字回传给客户端
						if(endTimestamp-(nowTimestamp+5*1000)>0){
							//计算出离过期还剩余的毫秒数返回给客户端
							order.put("REMAIN",endTimestamp-(nowTimestamp+5*1000));
						}else{
							//相反，则认为订单已过期，修改订单状态返回给客户端
							order.set("ORDERSTATE", OrderCode.OrderState.LATER);
						}
					}
					renderSuccess(order);
					return;
				}else{
					renderFailed("此订单不存在");
					return;
				}
			}
			
		}
	}
	
	/**
	 * 查询订单操作日志列表<br/>
	 * @param ORDERNUM 订单号
	 */
	public void track(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//查询订单的操作日志列表
				renderSuccess(service.getLogListByOrderNum(orderNum));
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 对订单进行评价
	 * @param ORDERNUM 订单号
	 * @param EVAL1 商品满意度
	 * @param EVAL2 配送速度满意度
	 * @param EVAL3 服务质量满意度
	 * @param CONTENT 评价内容
	 */
	public void eval(){
		String orderNum = getPara("ORDERNUM");
		int eval1 = getParaToInt("EVAL1",1);
		int eval2 = getParaToInt("EVAL2",1);
		int eval3 = getParaToInt("EVAL3",1);
		String content = getPara("CONTENT");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(!StrKit.isBlank(content)&&content.length()>=500){
			renderFailed("评论内容过长");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				if(service.doEval(orderNum, getCurrentUser().getInt("id"), eval1, eval2, eval3, content)){
					//更新订单评价状态为1：已评价
					order.set("evalState", 1).update();
					renderSuccess();
					return;
				}
				renderFailed("评价失败");
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
//	/**
//	 * 异常订单处理
//	 */
//	public void exceptionOrder(){
//		//t_bus_pay_bankno表查询   查询异常订单   及其金额
//		//  查询t_bus_pay_log_detail 和t_bus_pay_bankno 表，找出订单state为1的异常未处理订单和相应信息
//		String amount = null;  //订单金额
//		amount =new DecimalFormat("0.##").format(new BigDecimal(amount).multiply(new BigDecimal(100)));
//		Record re = new Record();
//		String cardNo = re.getStr("AcctNo");//收款人卡号
//		String cardName = re.getStr("OutAcctName");//收款人姓名
//		String bankName = re.getStr("InBankName");//银行名
//		String bankCode = re.getStr("InBankNo");//银行联行号   
//		String describe = "异常订单退款";
//		String orderNumber = "T"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
//		Map<String ,String> paraMap = null;
//	    try {
//	    	//组装请求体
//	        StringBuffer bodyXml = new StringBuffer();
//	        bodyXml.append("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
//	        bodyXml.append("<Result>");
//	        bodyXml.append("<OrderNumber>").append(ParamUtils.toString(orderNumber)).append("</OrderNumber>");
//	        bodyXml.append("<AcctNo>").append(ParamUtils.toString(PropKit.get("PINGAN.AcctNo"))).append("</AcctNo>");
//	        bodyXml.append("<BusiType>").append("00000").append("</BusiType>");
//	        bodyXml.append("<CorpId>").append("").append("</CorpId>");
//	        bodyXml.append("<CcyCode>").append("RMB").append("</CcyCode>");
//	        bodyXml.append("<TranAmount>").append(ParamUtils.toString(amount)).append("</TranAmount>");
//	        bodyXml.append("<InAcctNo>").append(ParamUtils.toString(cardNo)).append("</InAcctNo>");
//	        bodyXml.append("<InAcctName>").append(ParamUtils.toString(cardName)).append("</InAcctName>");
//	        bodyXml.append("<InAcctBankName>").append(ParamUtils.toString(bankName)).append("</InAcctBankName>");
//	        bodyXml.append("<InAcctBankNode>").append(ParamUtils.toString(bankCode)).append("</InAcctBankNode>");
//	        bodyXml.append("<Remark>").append(ParamUtils.toString(describe)).append("</Remark>");
//	        bodyXml.append("</Result>");
//	        //准备数据
//	        Map headMap = ParamUtils.toMap(new Object[][] { 
//	          { "MERCHANTS_ID", ParamUtils.toString(PropKit.get("PINGAN.MERCHANTS_ID")) }, 
//	          { "TRADE_CODE", ParamUtils.toString("KHKF03") }, 
//	          {"REQUEST_URL",ParamUtils.toString(PropKit.get("PINGAN.REQUEST_URL"))},
//	          { "REQUEST_ID", DatetimeKit.getFormatDate(new Date(), "yyyyMMddHHmmss") + CommonKit.randomNum(6) } });
//	        //获取请求头，组装请求体
//	        String headStr = PingAnUtils.getYQHead(ParamUtils.toString(Integer.valueOf(bodyXml.toString().getBytes(SysPara.GBK).length)), headMap);
//	        String requestStr = headStr + bodyXml;
//	        //发送请求 并获取响应
//	        Map respMap = PingAnUtils.send(headMap, requestStr);
//	        //根据响应代码判断成功与否
//	        if (!"000000".equals(ParamUtils.toString(respMap.get("RESP_CODE")))) {
//	        	renderFailed("查询响应失败");
//	        	return;
//	        }
//	        //获取响应体，并找到根节点
//	        String respXml = ParamUtils.toString(respMap.get("BUS_BODY"));
//	        Element element = org.nobject.common.xml.XmlUtils.toDocument(respXml).getRoot();
//	        
//	        String BussSeqNo = ParamUtils.toString(element.getElement("BussFlowNo").getText());
//	        String OrderNumber = ParamUtils.toString(element.getElement("OrderNumber").getText());
//	        //根据t_bus_pay_banknoout表判重
//	        Record rec = service.findMoneyOutByBussSeqNo(BussSeqNo);
//	        if(rec !=null){
//	        	renderFailed("重复提现");
//	        	return ;
//	        }
//	        //获取根节点信息，组装对象返回
//	        Record  record = new Record()
//	        		.set("BussSeqNo", BussSeqNo)
//	        		.set("AcctNo", cardNo)
//	        		.set("OrderNumber", OrderNumber)
//	        		.set("createDate", new Date());
//	        //保存到t_bus_pay_banknoout表中
//	        int count = service.saveMoneyOut(record);
//	        if(count==0){
//	        	 renderFailed("保存信息失败");
//	        	 return ;
//	        }
//	        renderSuccess(record); 
//	      } catch (Exception e) {
//	    	  renderFailed("查询失败");
//	      }
//	}
	
	/**
	 * 平安通道提现
	 */
//	public void moneyOut(){
//		String amount = getPara("AMOUNT");
//		if(StrKit.isBlank(amount)){
//			renderFailed("参数AMOUNT不能为空");
//    		return;
//		}
//		amount =new DecimalFormat("0.##").format(new BigDecimal(amount).multiply(new BigDecimal(100)));
//		Record re = service.findUserCardById(getCurrentUser().get("id"));
//		if(re == null){
//			renderFailed("该用户没有绑卡");
//			return;
//		}
//		String cardNo = re.getStr("cardNo");
//		String cardName = re.getStr("custName");//收款人姓名
//		String bankName = re.getStr("bankSite");
//		String bankCode = re.getStr("bankNo");//银行联行号
//		String phone = re.getStr("phoneNo");
//		String describe = "提现";
//		String province = re.getStr("province");
//		String city = re.getStr("city");
//		String orderNumber = "T"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
//		Map<String ,String> paraMap = null;
//	    try {
//	    	//组装请求体
//	        StringBuffer bodyXml = new StringBuffer();
//	        bodyXml.append("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
//	        bodyXml.append("<Result>");
//	        bodyXml.append("<OrderNumber>").append(ParamUtils.toString(orderNumber)).append("</OrderNumber>");
//	        bodyXml.append("<AcctNo>").append(ParamUtils.toString(PropKit.get("PINGAN.AcctNo"))).append("</AcctNo>");
//	        bodyXml.append("<BusiType>").append("00000").append("</BusiType>");
//	        bodyXml.append("<CorpId>").append("").append("</CorpId>");
//	        bodyXml.append("<CcyCode>").append("RMB").append("</CcyCode>");
//	        bodyXml.append("<TranAmount>").append(ParamUtils.toString(amount)).append("</TranAmount>");
//	        bodyXml.append("<InAcctNo>").append(ParamUtils.toString(cardNo)).append("</InAcctNo>");
//	        bodyXml.append("<InAcctName>").append(ParamUtils.toString(cardName)).append("</InAcctName>");
//	        bodyXml.append("<InAcctBankName>").append(ParamUtils.toString(bankName)).append("</InAcctBankName>");
//	        bodyXml.append("<InAcctBankNode>").append(ParamUtils.toString(bankCode)).append("</InAcctBankNode>");
//	        bodyXml.append("<Mobile>").append(ParamUtils.toString(phone)).append("</Mobile>");
//	        bodyXml.append("<Remark>").append(ParamUtils.toString(describe)).append("</Remark>");
//	        bodyXml.append("<InAcctProvinceName>").append(ParamUtils.toString(province)).append("</InAcctProvinceName>");
//	        bodyXml.append("<InAcctCityName>").append(ParamUtils.toString(city)).append("</InAcctCityName>");
//	        bodyXml.append("</Result>");
//	        //准备数据
//	        Map headMap = ParamUtils.toMap(new Object[][] { 
//	          { "MERCHANTS_ID", ParamUtils.toString(PropKit.get("PINGAN.MERCHANTS_ID")) }, 
//	          { "TRADE_CODE", ParamUtils.toString("KHKF03") }, 
//	          {"REQUEST_URL",ParamUtils.toString(PropKit.get("PINGAN.REQUEST_URL"))},
//	          { "REQUEST_ID", DatetimeKit.getFormatDate(new Date(), "yyyyMMddHHmmss") + CommonKit.randomNum(6) } });
//	        //获取请求头，组装请求体
//	        String headStr = PingAnUtils.getYQHead(ParamUtils.toString(Integer.valueOf(bodyXml.toString().getBytes(SysPara.GBK).length)), headMap);
//	        String requestStr = headStr + bodyXml;
//	        //发送请求 并获取响应
//	        Map respMap = PingAnUtils.send(headMap, requestStr);
//	        //根据响应代码判断成功与否
//	        if (!"000000".equals(ParamUtils.toString(respMap.get("RESP_CODE")))) {
//	        	renderFailed("查询响应失败");
//	        	return;
//	        }
//	        //获取响应体，并找到根节点
//	        String respXml = ParamUtils.toString(respMap.get("BUS_BODY"));
//	        Element element = org.nobject.common.xml.XmlUtils.toDocument(respXml).getRoot();
//	        
//	        String BussSeqNo = ParamUtils.toString(element.getElement("BussFlowNo").getText());
//	        String OrderNumber = ParamUtils.toString(element.getElement("OrderNumber").getText());
//	        //判重
//	        Record rec = service.findMoneyOutByBussSeqNo(BussSeqNo);
//	        if(rec !=null){
//	        	renderFailed("重复提现");
//	        	return ;
//	        }
//	        //获取根节点信息，组装对象返回
//	        Record  record = new Record()
//	        		.set("BussSeqNo", BussSeqNo)
//	        		.set("AcctNo", cardNo)
//	        		.set("OrderNumber", OrderNumber)
//	        		.set("createDate", new Date());
//	        //保存到表中
//	        int count = service.saveMoneyOut(record);
//	        if(count==0){
//	        	 renderFailed("保存信息失败");
//	        	 return ;
//	        }
//	        renderSuccess(record); 
//	      } catch (Exception e) {
//	    	  renderFailed("查询失败");
//	      }
//	}
	/**
	 * 平安通道提现/退款查询
	 */
//	public void moneyOutQuery(){
//		String OrderNumber = getPara("ORDERNUMBER");
//		String BussSeqNo = getPara("BUSSSEQNO");
//		if(StrKit.isBlank(OrderNumber)&&StrKit.isBlank(BussSeqNo)){
//			renderFailed("参数ORDERNUMBER,BUSSSEQNO不能同时为空");
//    		return;
//		}
//		Record record = null;
//	    try {
//	    	//准备body
//	        StringBuffer bodyXml = new StringBuffer();
//	        bodyXml.append("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
//	        bodyXml.append("<Result>");
//	        bodyXml.append("<OrderNumber>").append(ParamUtils.toString(OrderNumber)).append("</OrderNumber>");
//	        bodyXml.append("<AcctNo>").append(ParamUtils.toString(PropKit.get("PINGAN.AcctNo"))).append("</AcctNo>");
//	        bodyXml.append("<BussFlowNo>").append(ParamUtils.toString(OrderNumber)).append("</BussFlowNo>");
//	        bodyXml.append("</Result>");
//	        //准备请求头数据
//	        Map headMap = ParamUtils.toMap(new Object[][] { 
//	          { "MERCHANTS_ID", ParamUtils.toString(PropKit.get("PINGAN.MERCHANTS_ID")) }, 
//	          { "TRADE_CODE", ParamUtils.toString("KHKF04") }, 
//	          {"REQUEST_URL",ParamUtils.toString(PropKit.get("PINGAN.REQUEST_URL"))},
//	          { "REQUEST_ID", DatetimeKit.getFormatDate(new Date(), "yyyyMMddHHmmss") + CommonKit.randomNum(6) } });
//	        //获取请求头
//	        String headStr = PingAnUtils.getYQHead(ParamUtils.toString(Integer.valueOf(bodyXml.toString().getBytes(SysPara.GBK).length)), headMap);
//	        //组织报文
//	        String requestStr = headStr + bodyXml;
//	        //发送并获取返回
//	        Map respMap = PingAnUtils.send(headMap, requestStr);
//	        if (!"000000".equals(ParamUtils.toString(respMap.get("RESP_CODE")))) {
//	        	renderFailed("响应失败");
//	        	return ;
//	        }
//	        //获取响应体
//	        String respXml = ParamUtils.toString(respMap.get("BUS_BODY"));
//	        //获取根节点
//	        Element element = org.nobject.common.xml.XmlUtils.toDocument(respXml).getRoot();
//	        //如果状态码是20  则交易成功，如果是30  交易处理中，如果是其他  交易失败
//	        if ("20".equals(ParamUtils.toString(element.getElement("Status").getText()))) {
//	        	//交易成功 
//	        }else if("30".equals(ParamUtils.toString(element.getElement("Status").getText()))){
//	        	//交易已受理  正在处理中  
//	        }else{
//	        	//交易失败
//	        	renderFailed("交易失败");
//	        	 return;
//	        }
//	        //组装返回信息
//	        record = new Record()
//	        		.set("BussFlowNo", ParamUtils.toString(element.getElement("BussFlowNo").getText()))
//	        		.set("TranFlowNo", ParamUtils.toString(element.getElement("TranFlowNo").getText()))
//	        		.set("OrderNumber", ParamUtils.toString(element.getElement("OrderNumber").getText()))
//	        		.set("Status", ParamUtils.toString(element.getElement("Status").getText()))
//	        		.set("RetCode", ParamUtils.toString(element.getElement("RetCode").getText()))
//	        		.set("RetMsg", ParamUtils.toString(element.getElement("RetMsg").getText()))
//	        		.set("SettleDate", ParamUtils.toString(element.getElement("SettleDate").getText()))
//	        		.set("Remark", ParamUtils.toString(element.getElement("Remark").getText()))
//	        		.set("InAcctNo", ParamUtils.toString(element.getElement("InAcctNo").getText()))
//	        		.set("InAcctName", ParamUtils.toString(element.getElement("InAcctName").getText()))
//	        		.set("CcyCode", ParamUtils.toString(element.getElement("CcyCode").getText()))
//	        		.set("Mobile", ParamUtils.toString(element.getElement("Mobile").getText()))
//	        		.set("TranAmount", new DecimalFormat("0.##").format(new BigDecimal(ParamUtils.toString(element.getElement("TranAmount").getText())).multiply(new BigDecimal(100))) );
//	      	//保存查询信息
//	        int count = service.doRedem(record,getCurrentUser().get("id"));
//	        if(count == 2){
//	        	 renderFailed("查找用户信息失败");
//	        	 return ;
//	        }else if(count == 3){
//	        	 renderFailed("更改用户余额失败");
//	        	 return;
//	        }else if(count == 4){
//	        	 renderFailed("记录失败");
//	        	 return;
//	        }
//	        renderSuccess(record); 
//	      } catch (Exception e) {
//	    	  renderFailed("查询失败");
//	      }
//	}
	
	

	/*
	 * 创建用户查询商品订单快递信息的方法
	 */
	public  void getDelivelyInformation() {
		String OrderNumber = getPara("ORDERNUM");
		if(StrKit.isBlank(OrderNumber)){
			renderFailed("参数ORDERNUMBER不能为空");
    		return;
		}
//		String charset = "ANE";
//		String logisticsNumber = "210001633605";
//		OrderNumber = "439354361879";
		
		//从数据库查询物流信息
		Record record = service.findWuliuByOrderNum(OrderNumber);
		if(record==null){
			renderFailed("查询快递失败");
    		return;
		}
		String logisticsNumber = record.get("logisticCode");
		String charset = record.get("charset");
		if ( "0000".equals(charset) ){
			Record re = new Record();
			re.set("LogisticCode",logisticsNumber )
			.set("list", new ArrayList<>());
			renderSuccess(re);
			return;
		}else {
			// 调用快递鸟快递信息查询接口返回信息
			try {
				String info = KdniaoTrackQueryAPI.getOrderTracesByJson(OrderNumber, charset, logisticsNumber);
				System.out.println("KdniaoTrackQueryAPI.getOrderTracesByJson(null, charset, logisticsNumber)===>"
						+ KdniaoTrackQueryAPI.getOrderTracesByJson(null, charset, logisticsNumber));
				if (info != null && info.hashCode() != 0) {
					
					// 将得到的快递鸟返回的订单的物流JSON数据转换成Map<String,Object>类型数据
					JSONObject json = JSONObject.fromObject(info);
					
					if((Boolean)json.get("Success")){
						String obj = json.get("Traces").toString();
						List<String> map = new ArrayList<String>();
						obj = obj.substring(1, obj.length()-1);
						String[] split = obj.split("},");
						for(int i = 0; i<split.length;i++){
							if(i!=(split.length-1)){
								split[i] = split[i]+"}";
							}
							map.add(split[i]);
						}
						Record re = new Record();
						re.set("OrderCode",ParamUtils.toString(json.get("OrderCode")) )
						.set("ShipperCode",ParamUtils.toString(json.get("ShipperCode")) )
						.set("LogisticCode",ParamUtils.toString(json.get("LogisticCode")) )
						.set("State",ParamUtils.toString(json.get("State")) )
						.set("list", map);
						renderSuccess(re);
						return;
					}else{
						renderFailed(ParamUtils.toString(json.get("Reason")));
						return ;
						
					}
				} else {
					renderFailed("订单物流信息查询失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		

	}
	/**
	 * 评论列表
	 */
	public void commentlist(){
		//查询用户评价列表
		List<Record> list = service.findCommentByuserid(getCurrentUser().getInt("id"));
		if(list.size()>0&&list!=null){
			for(Record re : list){
				
				//拼接轮播图
				List<Record> lists = service.findImageByLunBoNum(re.getStr("LunBoNum"));
				if(lists!=null&&lists.size()>0){
					List<String> listss = new ArrayList<String>();
					for(Record rr : lists){
						listss.add(rr.getStr("thumb"));
					}
					re.set("thumb", listss);
				}
				//查询评价的商品信息
				String str = re.get("orderNum");
				str = str.subSequence(0, 1).toString();
				int id = re.get("specid");
				if("G".equals(str)){
					//普通订单 t_bus_goods_sale 的id
					
					List<Record> speclist = service.findSpecByids(id+"");
					if(speclist!=null&&speclist.size()>0){
						for(Record res : speclist){
							re.set("goods", res);
						}
					}
				}else if("D".equals(str)){
					//兑换订单 t_bus_ege_goods_spec的id
					Record res = service.findExchangeByid(id);
					if(res!=null){
						re.set("good", res);
					}
				}
				
			}
			Record res = new Record();
			res.set("list", list).set("user", getCurrentUser());
			renderSuccess(res);
			return;
		}else{
			renderFailed("还没有评论的商品");
			return ;
		}
	}
	/**
	 * 查询订单简单详情
	 */
	public void orderDetail(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
			return;
		}
		String type = orderNum.subSequence(0, 1).toString();
		Record rec = null;
		if("G".equals(type)){
			//普通订单
			//根据普通订单号查询商品详情
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				if(order.getInt("orderState")==3){
					String specsidss = order.get("specsid");
					int isSpike = order.getInt("isSpike");
					List<Record> list = service.findSpecByids(specsidss);
					if(list.size()>0&&list!=null){
						if(isSpike == 1){
							Record resc = service.findSpikeByGoodid(list.get(0).getInt("goodsid"));
							if(resc!=null){
								list.get(0).set("saleprice", resc.getDouble("spikePrice"));
							}
						}
						Record re = new Record();
						re.set("type", 2);
						re.set("LIST", list);
						renderSuccess(re);
						return ;
					}
				}
			}
			renderFailed("未查到该笔订单");
			return;
		}else if("D".equals(type)){
			//兑换订单
			//根据订单号查询商品详情
			rec = service.findExchanegGoodByOrderNum(orderNum,getCurrentUser().getInt("id"));
		}else {
			//团购订单
			rec = service.findGroupGoodByOrderNum(orderNum,getCurrentUser().getInt("id"));
		}
		if(rec!=null){
			rec.set("type", 1);
			renderSuccess(rec);
			return;
		}else{
			renderFailed("未查到此订单");
			return;
		}
		
	}
	
	
	/**
	 * 微信小程序支付<br/>
	 * 首先验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * @param ORDERNUM 要支付的订单号
	 * @param CODE 如果是验证短信  此为发送短信返回的验证码
	 * @param TIME 如果是验证短信  此为发送短信返回的时间日期
	 * 
	 */
	public void pay1(){
		//获取订单支付方式
		String flag=getPara("FLAG");
		//获取OPENID
		String openid=getPara("OPENID");
		if(StrKit.isBlank(openid)){
			renderFailed("参数OPENID不能为空");
    		return;
		}
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}
		//获取配置项
		String appid =PropKit.get("MPWXPAY.appid");
		String mch_id =PropKit.get("MPWXPAY.mch_id");
		String paternerKey =PropKit.get("MPWXPAY.paternerkey");
		String notify_url =PropKit.get("MPWXPAY.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		if (StrKit.isBlank(remoteip)) {
			remoteip = "127.0.0.1";
        }
		//截取订单首字母，判断订单类型
		String str = orderNum.subSequence(0, 1).toString();
		if("G".equals(str)){
			///普通订单
			//查询订单详情并以此验证订单号
			Order order = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			if(order.getInt("isSpike") == 1){
				//数据准备
				String id = order.get("goodsid");
				String[] times = order.getTimestamp("startDate").toString().split(" ");
				int count  = service.checkSpikeOrderDate(id,times);
				if(count == -1){
					renderFailed("您的订单已过秒杀时间段,无法支付");
					return;
				}
			}
			//订单总金额
			double amount = order.get("amount");
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				//有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("SIGN", appSign));
				return;
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
		}else if("D".equals(str)){
			///兑换订单
			//验证顶
			OrderE order = service.getExchangeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			
			//计算订单总金额，
			double amount = order.getDouble("amount");
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("SIGN", appSign));
				return;
					
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}		
		}else if("Z".equals(str)){
			///兑换订单
			//验证顶
			OrderZ order = service.getRechargeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			
			//计算订单总金额，
			double amount = order.getDouble("amount");
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("SIGN", appSign));
				return;
					
			}		
		}
		
		
		
	}
	
	/**
	 * APP支付<br/>
	 * 首先验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * @param FLAG 支付方式
	 * @param ORDERNUM 要支付的订单号
	 */
	public void pay2(){
		//获取订单支付方式
		String flag=getPara("FLAG");
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if("0".equals(flag)){
			renderFailed("请选择支付方式");
    		return;
		}
		
		//获取配置项
		//微信
		String appid =PropKit.get("APPWXPAY.appid");
		String mch_id =PropKit.get("MPWXPAY.mch_id");
		String paternerKey =PropKit.get("MPWXPAY.paternerkey");
		String notify_url =PropKit.get("MPWXPAY.goodsOrderNotifyUrl");
		//支付宝
		String gateway=PropKit.get("applipay.url");
		String app_id=PropKit.get("appalipay.partner");
		String privateKey=PropKit.get("appalipay.privateKey");
		String alipayPublicKey=PropKit.get("appalipay.alipayPublicKey");
		String charset=PropKit.get("applipay.charset");
		String sign_type=PropKit.get("applipay.signType");
		String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
		String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
		String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
		String alipay_notify_url =PropKit.get("appalipay.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		if (StrKit.isBlank(remoteip)) {
			remoteip = "127.0.0.1";
        }
		//截取订单首字母，判断订单类型
		String str = orderNum.subSequence(0, 1).toString();
		
		
		///普通订单
		if("G".equals(str)){
			//查询订单详情并以此验证订单号
			Order order = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			if(order.getInt("isSpike") == 1){
				//数据准备
				String id = order.get("goodsid");
				String[] times = order.getTimestamp("startDate").toString().split(" ");
				int count  = service.checkSpikeOrderDate(id,times);
				if(count == -1){
					renderFailed("您的订单已过秒杀时间段,无法支付");
					return;
				}
			}
			//订单总金额
			double amount = order.get("amount");
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//获取订单总金额，并转换为以“元”为单位
			String amountStr1 = String.valueOf(Double.valueOf(amount));
			
			
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				///微信支付
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "APP"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		       
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appid", appid);
		        data.put("partnerid", mch_id);
		        data.put("prepayid", prepay_id);
		        data.put("package", "Sign=WXPay");
		        data.put("noncestr", nonceStr);
		        data.put("timestamp", timestamp);
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        String jsonStr = JsonUtils.toJson(data);
		        renderSuccess(ResultMap.newInstance().put("ORDERINFO", jsonStr).put("PROVIDER", "wxpay").put("ORDERNUM", orderNum).getAttrs());
				return;
				
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
				///支付宝支付
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
				AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
				model.setBody("亿拼惠");
				model.setSubject("亿拼惠");
				model.setOutTradeNo(orderNum);
				model.setTimeoutExpress("30m");
				model.setTotalAmount(amountStr1);
				model.setProductCode("QUICK_MSECURITY_PAY");
				//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
				AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
				request.setBizModel(model);
				request.setNotifyUrl(alipay_notify_url);
				try {
					//构造client
					AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
				        //这里和普通的接口调用不同，使用的是sdkExecute
				        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
				        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
				      //更新订单支付方式为支付宝
						order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
						//将结果返回给客户端
						renderSuccess(ResultMap.newInstance().put("ORDERINFO", response.getBody()).put("PROVIDER", "alipay").put("ORDERNUM", orderNum).getAttrs());
				    } catch (AlipayApiException e) {
				        e.printStackTrace();
				}
				
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
		
		}else if("D".equals(str)){
			///兑换订单
			//验证订单
			OrderE order = service.getExchangeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			//订单总金额
			double amount = order.get("amount");
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//获取订单总金额，并转换为以“元”为单位
			String amountStr1 = String.valueOf(Double.valueOf(amount));
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				///微信支付
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "APP"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		       
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appid", appid);
		        data.put("partnerid", mch_id);
		        data.put("prepayid", prepay_id);
		        data.put("package", "Sign=WXPay");
		        data.put("noncestr", nonceStr);
		        data.put("timestamp", timestamp);
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        String jsonStr = JsonUtils.toJson(data);
		        renderSuccess(ResultMap.newInstance().put("ORDERINFO", jsonStr).put("PROVIDER", "wxpay").put("ORDERNUM", orderNum).getAttrs());
				return;
					
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){///支付宝支付
				
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
				AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
				model.setBody("亿拼惠兑换");
				model.setSubject("亿拼惠");
				model.setOutTradeNo(orderNum);
				model.setTimeoutExpress("30m");
				model.setTotalAmount(amountStr1);
				model.setProductCode("QUICK_MSECURITY_PAY");
				//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
				AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
				request.setBizModel(model);
				request.setNotifyUrl(alipay_notify_url);
				try {
					//构造client
					AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
				        //这里和普通的接口调用不同，使用的是sdkExecute
				        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
				        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
				      //更新订单支付方式为支付宝
						order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
						//将结果返回给客户端
						renderSuccess(ResultMap.newInstance().put("ORDERINFO", response.getBody()).put("PROVIDER", "alipay").put("ORDERNUM", orderNum).getAttrs());
				    } catch (AlipayApiException e) {
				        e.printStackTrace();
				}
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}
		}else if("Z".equals(str)){
			///兑换订单
			//验证订单
			OrderZ order = service.getRechargeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			//订单总金额
			double amount = order.get("amount");
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//获取订单总金额，并转换为以“元”为单位
			String amountStr1 = String.valueOf(Double.valueOf(amount));
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				///微信支付
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "APP"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("time_start", startDate);//用户OPENID
		        params.put("time_expire", expireDate);//用户OPENID
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		       
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appid", appid);
		        data.put("partnerid", mch_id);
		        data.put("prepayid", prepay_id);
		        data.put("package", "Sign=WXPay");
		        data.put("noncestr", nonceStr);
		        data.put("timestamp", timestamp);
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        String jsonStr = JsonUtils.toJson(data);
		        renderSuccess(ResultMap.newInstance().put("ORDERINFO", jsonStr).put("PROVIDER", "wxpay").put("ORDERNUM", orderNum).getAttrs());
				return;
					
			}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){///支付宝支付
				
				//构造client
				CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
				//设置网关地址
				certAlipayRequest.setServerUrl(gateway);
				//设置应用Id
				certAlipayRequest.setAppId(app_id);
				//设置应用私钥
				certAlipayRequest.setPrivateKey(privateKey);
				//设置请求格式，固定值json
				certAlipayRequest.setFormat("json");
				//设置字符集
				certAlipayRequest.setCharset(charset);
				//设置签名类型
				certAlipayRequest.setSignType(sign_type);
				//设置应用公钥证书路径
				certAlipayRequest.setCertPath(app_cert_path);
				//设置支付宝公钥证书路径
				certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
				//设置支付宝根证书路径
				certAlipayRequest.setRootCertPath(alipay_root_cert_path);
				//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
				AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
				model.setBody("亿拼惠充值");
				model.setSubject("亿拼惠");
				model.setOutTradeNo(orderNum);
				model.setTimeoutExpress("30m");
				model.setTotalAmount(amountStr1);
				model.setProductCode("QUICK_MSECURITY_PAY");
				//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
				AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
				request.setBizModel(model);
				request.setNotifyUrl(alipay_notify_url);
				try {
					//构造client
					AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
				        //这里和普通的接口调用不同，使用的是sdkExecute
				        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
				        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
				      //更新订单支付方式为支付宝
						order.set("paytype", OrderCode.OrderPayMethod.ALIPAY).update();
						//将结果返回给客户端
						renderSuccess(ResultMap.newInstance().put("ORDERINFO", response.getBody()).put("PROVIDER", "alipay").put("ORDERNUM", orderNum).getAttrs());
				    } catch (AlipayApiException e) {
				        e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 微信公众号支付<br/>
	 * 首先验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * @param ORDERNUM 要支付的订单号
	 * @param CODE 如果是验证短信  此为发送短信返回的验证码
	 * @param TIME 如果是验证短信  此为发送短信返回的时间日期
	 * 
	 */
	public void pay3(){
		//获取订单支付方式
		String flag=getPara("FLAG");
		//获取OPENID
		String openid=getPara("OPENID");
		if(StrKit.isBlank(openid)){
			renderFailed("参数OPENID不能为空");
    		return;
		}
		//获取订单号
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}
		//获取配置项
		String appid =PropKit.get("PWXPAY.appid");
		String mch_id =PropKit.get("PWXPAY.mch_id");
		String paternerKey =PropKit.get("PWXPAY.paternerkey");
		String notify_url =PropKit.get("PWXPAY.goodsOrderNotifyUrl");
		//获取客户端IP
		String remoteip = EncryUtils.getRealIp(getRequest());
		if (StrKit.isBlank(remoteip)) {
			remoteip = "127.0.0.1";
        }
		//截取订单首字母，判断订单类型
		String str = orderNum.subSequence(0, 1).toString();
		if("G".equals(str)){
			///普通订单
			//查询订单详情并以此验证订单号
			Order order = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			if(order.getInt("isSpike") == 1){
				//数据准备
				String id = order.get("goodsid");
				String[] times = order.getTimestamp("startDate").toString().split(" ");
				int count  = service.checkSpikeOrderDate(id,times);
				if(count == -1){
					renderFailed("您的订单已过秒杀时间段,无法支付");
					return;
				}
			}
			//订单总金额
			double amount = order.get("amount");
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//获取订单总金额，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				//有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
	//	        params.put("time_start", startDate);//订单生效时间
	//	        params.put("time_expire", expireDate);//订单失效时间
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("公众号统一下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		      //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
		       //记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		     // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("APPID", appid)
						.put("SIGN", appSign));
				return;
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}	
		}else if("D".equals(str)){
			///兑换订单
			//验证顶
			OrderE order = service.getExchangeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			//计算订单总金额
			double amount = order.getDouble("amount");
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
	//	        params.put("time_start", startDate);//订单生效时间
	//	        params.put("time_expire", expireDate);//订单失效时间
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("公众号统一下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		        //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
				//记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		        // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("APPID", appid)
						.put("SIGN", appSign));
				return;
			}else if (payMethod == OrderCode.OrderPayMethod.BALANCE1) {
				//将订单改为余额支付
				//更新订单支付方式为余额
				order.set("paytype", OrderCode.OrderPayMethod.BALANCE1).update();
				//查询用户余额  判断是否充足
				User user=service.findUserByid(getCurrentUser().getInt("id"));
				if(user!=null){
		    		//查询成功
		    		//账户余额
					Double money = user.getDouble("money");
					if(Double.compare(money, amount)==-1){
						//余额不足
						renderFailed("余额不足");
						return;
					}
					//支付
					int count;
					try {
						count = service.chanegMoney(user,amount,orderNum,order);
						if(count==1){
				    		renderSuccess("支付成功");
				    		return;
				    	}else{
				    		//支付失败
				    		renderFailed("支付失败");
				    		return;
				    	}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//支付失败
			    		renderFailed("支付失败");
			    		return;
					}
					
		    	}else{
		    		//查询余额失败
		    		logger.info(">>>>>>>>>>>>>>>查询用户余额失败");
		    		renderFailed("网络错误，请稍后重试");
		    		return;
		    	}
			}		
				
		}else if("Z".equals(str)){
			///兑换订单
			//验证顶
			OrderZ order = service.getRechargeOrdersByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order==null){
				renderFailed("订单不存在");
	    		return;
			}
			//验证订单是否有效
			
			if(DatetimeKit.compareDate(order.getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
				return;
			}
			//计算订单总金额
			double amount = order.getDouble("amount");
			
			//根据用户所选择的支付方式不同作不同处理
			int payMethod = Integer.valueOf(flag);
			if (payMethod == OrderCode.OrderPayMethod.WEIXIN) {
				//，并转换为以“分”为单位
				String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
				
				//获取订单有效时间
				String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"),"yyyyMMddHHmmss");
				String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"),"yyyyMMddHHmmss");
				
				Map<String,String> params = new HashMap<String,String>();
		        params.put("appid", appid);
		        params.put("mch_id", mch_id);
		        params.put("body", "亿拼惠");
		        params.put("out_trade_no", orderNum); //订单编号
		        params.put("total_fee", amountStr); //订单金额  单位为分
		        params.put("spbill_create_ip", remoteip);  //终端ip
		        params.put("trade_type", "JSAPI"); //交易类型app：手机app支付，NATIVE：返回支付连接，可转成二维码客户扫描支付
		        params.put("nonce_str",  System.currentTimeMillis() / 1000 + ""); //随机字符串
		        params.put("notify_url", notify_url); //支付后通知回调地址
		        params.put("openid", openid);//用户OPENID
	//	        params.put("time_start", startDate);//订单生效时间
	//	        params.put("time_expire", expireDate);//订单失效时间
		        String sign = PaymentKit.createSign(params, paternerKey);    //生成签名
		        params.put("sign", sign);
		       
		        //下单
		        String xmlResult = PaymentApi.pushOrder(params);
		        System.out.println("公众号统一下单后结果"+xmlResult);
		        Map<String,String> result = PaymentKit.xmlToMap(xmlResult);
		        
		        String return_code = result.get("return_code");
		        String return_msg = result.get("return_msg");
		        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
		        	renderFailed(return_msg+"0");
		            return;
		        }
		        String result_code = result.get("result_code");
		        String err_code_des=result.get("err_code_des");
		        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
		            renderFailed(err_code_des+"1");
		            return;
		        }
		        //更新订单支付方式为微信
				order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
				//记录订单
		        new OrderPayAPIRecord().set("orderNum", orderNum)
		        .set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", 1)
				.set("flag", 1)
				.save();
		        // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
		        String prepay_id = result.get("prepay_id");
		        
		        String nonceStr = System.currentTimeMillis() + "";
		        String timestamp=DatetimeKit.getTimestamp();
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("appId", appid);
		        data.put("timeStamp", timestamp);
		        data.put("nonceStr", nonceStr);
		        data.put("package", "prepay_id="+prepay_id);
		        data.put("signType", "MD5");
		        String appSign = PaymentKit.createSign(data, paternerKey);
		        data.put("sign", appSign);
		        renderSuccess(ResultMap.newInstance()
						.put("ORDERNUM",orderNum)
						.put("PACKAGE", "prepay_id="+prepay_id)
						.put("NONCESTR", nonceStr)
						.put("TIMESTAMP", timestamp)
						.put("APPID", appid)
						.put("SIGN", appSign));
				return;
			}		
				
		}
		
		
		
	}
	
	/**
	 * 申请退款
	 */
	public void applyRefund() {
		//获取订单号
		String orderStateStr=getPara("ORDERSTATE");
		String orderNum = getPara("ORDERNUM");
		String refundReason = getPara("REFUNDREASON");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if (StrKit.isBlank(orderStateStr)) {
			renderFailed("参数ORDERSTATE不能为空");
    		return;
		}
		Order order=service.getOrderByOrderNum(orderNum);
		if (order==null) {
			renderFailed("订单不存在");
			return;
		}else if (order.getInt("tuistate")!=0) {
			renderFailed("操作异常，请刷新后重试");
			return;
		}
		
		int orderState=Integer.valueOf(orderStateStr);
		int userid=getCurrentUser().getInt("id");
		try {
			if (service.updateRefund(orderNum,OrderCode.OrderTuiState.APPLYREFUNDING,orderState, userid, OrderCode.OrderLogType.APPLYREFUND, "用户"+userid, "申请退款", "用户向后台申请退款",refundReason)) {
				renderSuccess("退款申请成功，请等待审核");
			}else {
				renderFailed("申请失败，请稍后再试");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("申请失败，请稍后重试");
		}
	}
}
